바이트코드가 별도로 생성
된다.필드, 생성자, 메서드 선언
이 올 수 있다.package ch09.sec02.ex;
public class A {
class B {
int field1 = 1;
static int field2 = 2;
B() {
System.out.println("B 생성자 실행");
}
void method1() {
System.out.println("B-method1() 실행");
}
static void method2() {
System.out.println("B-static-method2() 실행");
}
}
}
package ch09.sec02.ex;
public class Main {
public static void main(String[] args) {
A.B.method2(); // B-static-method2() 실행
A a = new A();
A.B b = a.new B(); // B 생성자 실행
}
}
static
키워드를 붙여서 정적 멤버 클래스로 만든다.package ch09.sec02.ex;
public class C {
static class D {
D() {
System.out.println("D-생성자 실행");
}
}
// 인스턴스 필드
D field1 = new D();
// 정적 필드
static D filed2 = new D();
C() {
System.out.println("C-생성자 실행");
D d = new D();
}
void method1() {
D d = new D();
}
static void method2() {
System.out.println("method2() Call!");
D d = new D();
}
}
package ch09.sec02.ex;
public class Main {
public static void main(String[] args) {
// C.method2(); // D-생성자 실행
// C.D filed2 = C.filed2; // D-생성자 실행
/*
D-생성자 실행
D-생성자 실행
C-생성자 실행
D-생성자 실행
*/
C.D fieldA = new C().field1; // 정적 필드 초기화 -> 인스턴스 필드 초기화 -> 생성자 호출
System.out.println("-----");
/*
D-생성자 실행
C-생성자 실행
D-생성자 실행
*/
C.D fieldB = new C().field1; // 인스턴스 필드 초기화 -> 생성자 호출
}
}
💡 클래스 로딩 시점
- 클래스의 인스턴스가 생성될 때
- 클래스의 정적 변수가 사용될 때
- 클래스의 정적 메서드가 호출될 때
출처👉클래스는 언제 로딩되고 초기화되는가? (feat. 싱글톤)
final 특성을 가지고 있어 값을 읽을 수만 있고 수정할 수 없다.
package ch09.sec02.ex;
public class E {
public E() {
System.out.println("E 객체 생성");
}
void method() {
int var = 1;
class F {
int field = 1;
public F() {
System.out.println("F 객체 생성");
}
void method1() {
// var = 2; // Variable 'var' is accessed from within inner class, needs to be final or effectively final
field = 2;
System.out.println("F객체 field 값: " + field);
}
static void method2() {
System.out.println("F객체 static 메서드 실행!");
}
}
F f = new F();
f.method1();
F.method2();
}
}
package ch09.sec02.ex;
public class Main {
public static void main(String[] args) {
E e = new E(); // E 객체 생성
System.out.println(" --- ");
e.method(); // F 객체 생성
}
}
💡참고