Intro
Class / Object
public class ExClass { // class 클래스명 int num = 3; // (1) 필드 void learn() {...} // (2) 메서드 ExClass {...} // (3) 생성자 class ExClass2 {...} // (4) 이너 클래스 }
new
키워드를 이용하여 실제 객체를 생성하여 클래스 멤버에 접근 가능.클래스명 참조변수명 = new 생성자(); // 객체 생성 예시 Person p = new Person(); // Person 클래스로 만들어진 p 인스턴스
.
을 활용하여 특정 인스턴스 객체의 필드와 메서드, 즉 객체의 멤버들에 접근할 수 있음.// 객체의 멤버에 접근하기.java 참조 변수명.필드명 // 필드값 불러오기 참조 변수명.메서드명() // 메서드 호출
Field / Method
클래스에 포함된 변수, 객체의 속성을 정의할 때 사용.
static
키워드를 통해 선언하는 변수. 공통된 저장공간을 공유함.클래스명.클래스변수명
을 통해 사용이 가능new 생성자()
를 통해 인스턴스가 생성되면서 같이 생성됨.class Example { // => 클래스 영역 int instanceVariable; // 인스턴스 변수 static int classVariable; // 클래스 변수(static 변수, 공유변수) ⠀⠀⠀⠀⠀ void method() { // => 메서드 영역 int localVariable = 0; // 지역 변수. {}블록 안에서만 유효 } } // `field`에 포함되는 변수는 클래스 변수와 인스턴스 변수이다. // 그 중 `static`키워드를 포함하면 클래스, 그렇지 않으면 인스턴스 변수이다. // 필드를 제외한 메서드 내에 포함되는 모든 변수는 지역변수.
static
이 붙어있으면 정적 멤버(static member)라고 함.public class Test { public static void main(String[] args) { StField stField1 = new StField(); // 객체1 생성 StField stField2 = new StField(); // 객체2 생성 stField1.num1 = 60; stField2.num1 = 90; System.out.println(stField1.num1); // 60 System.out.println(stField2.num1); // 90 stField1.num2 = 150; stField2.num2 = 250; System.out.println(stField1.num2); // 250 System.out.println(stField2.num2); // 250 } } class StField { int num1 = 30; // 인스턴스 변수 static int num2 = 50; // 클래스 변수 }
특정 작업을 수행하는 일련의 명령문들의 집합. 클래스의 기능
{}
안에 해당 메서드가 호출되었을 때 수행하야 하는 일련의 작업을 표시. 관례적으로 메서드명은 소문자로 표현.void
키워드가 없는 경우 반드시 메서드 바디에 return
문이 존재. 결과값은 반드시 반환타입과 일치하거나 자동변환 가능한 타입이어야 함.자바제어자 반환타입 메서드명(매개 변수) { // 메서드 시그니처 메서드 내용 // 메서드 바디 }
void printMethod() { // 반환타입이 void인 메서드 System.out.println("this is method"); }
int getNum() { // 매개변수가 없는 메서드 return 10; }
double multiply(int x, double y) { // 매개변수가 있는 메서드 double result = x * y; return result; }
메서드이름(매개변수1, 매개변수2, ...); // 메서드 호출방법 ⠀ void printMethod(); // this is method int getNum(); // 10 double multiply(3, 2.5); // 7.5
public class Overloading { public static void main(String[] args) { Math m = new Math(); // 객체 생성 m.calculate(); // 메서드 호출 m.calculate(5); m.calculate(4,3); m.calculate(7.5, 1.5); } } class Math { public void calculate() { // 메서드 오버로딩 System.out.println("계산"); } public void calculate(int x) { System.out.println("입력 = " x); } public void calculate(int x, int y) { System.out.println("더하기 = " x + y); } public void calculate(double x, double y) { System.out.println("나누기 = " x / y); } }
Constructor
인스턴스 변수들을 초기화하기 위해 사용하는 특수한 메서드
인스턴스를 생성하는 것은 new
키워드.
클래스명(매개변수) { // 생성자 기본 구조, 매개변수는 없을 수도 있음. ...... }
public class ConstructorEx { public static void main(String[] args) { Con con1 = new Con(); Con con2 = new Con("second"); Con con3 = new Con(3,2); } } class Con { Con() { // (1) 생성자 오버로딩 System.out.println("생성자1"); } Con(String str) { // (2) System.out.println("생성자2"); } Con(int a, int b) { // (3) System.out.println("생성자3"); } }
public class VarCon { public static void main(String[] args) { Book b = new Book("Clean code", "공학서적", 584); System.out.println("이 책은 " + b.bookName() + ", 페이지 수는 " + b.pages + "입니다."); } } class Book { private String bookName; private String bookField; int pages; public Book(String bookName, String bookField, int pages) { this.bookName = bookName; this.bookFiled = bookField; this.pages = pages; } public String bookName() { return bookName; } }
this
this
를 이용하여 인스턴스 자신의 변수에 접근.this.bookName = bookName; // this 키워드를 사용하여 구분 bookname = bookname; // 둘 다 지역변수로 간주
this()
this()
는 생성자의 내부에서만 사용 가능.this()
는 반드시 생성자의 첫 줄에 위치.
public class TestThis { public static void main(String[] args) { This example = new This(); This example2 = new This(1); } } ⠀ class This { public This() { System.out.println("기본 생성자"); }; ⠀ public This(int x) { this(); // "기본 생성자" System.out.println("매개변수가 있는 생성자"); } } // 출력 기본 생성자 기본 생성자 매개변수가 있는 생성자
Inner Class
클래스 내부에 선언된 클래스
class Outer { // 외부 클래스 class Inner { // (1) 인스턴스 내부 클래스 } static class StaticInner { // (2) 정적 내부 클래스 } void run() { class LocalInner { // (3) 지역 내부 클래스 } } }
인스턴스 내부 클래스
선언 위치 사용 가능한 변수 외부 클래스의 멤버변수 위치에 선언 외부 인스턴스 변수, 외부 전역 변수
정적 내부 클래스
선언 위치 사용 가능한 변수 외부 클래스의 멤버변수 위치에 선언 외부 전역 변수
지역 내부 클래스
선언 위치 사용 가능한 변수 외부 클래스의 메서드 혹은 초기화 블럭 내부 외부 인스턴스 변수, 외부 전역 변수
익명 내부 클래스
선언 위치 사용 가능한 변수 클래스의 선언과 객체의 생성 동시에 진행. 일회용 외부 인스턴스 변수, 외부 전역 변수
인스턴스 내부 클래스
정적 내부 클래스
static
키워드 사용함.class Outer { //외부 클래스 int num1 = 10; void printNum() { int num2 = 20; class LocalInClass { //지역 내부 클래스 void getPrint() { System.out.println(num1); System.out.println(num2); } } LocalInClass localInClass = new LocalInClass(); localInClass.getPrint(); } } public class Main { public static void main(String[] args) { Outer o = new Outer(); o.printNum(); } } // 출력 10 20