Study/Java

[JAVA] 내부 클래스

토기발 2022. 11. 13. 23:21

 

자바의 정석을 읽으며 정리를 위해 포스팅합니다.

혹시 틀린 부분이 있다면 말씀 부탁드립니다^^~

 


 

내부 클래스란?: 클래스 내에 선언된 클래스

내부 클래스를 선언하는 이유?: 두 클래스가 긴밀한 관계에 있기 때문.

두 클래스의 멤버들 간에 서로 쉽게 접근할 수 있다는 장점과 외부에는 불필요한 클래스를 감춤으로써 코드의 복잡성을 줄일 수 있다.

 

 

class A{
...
}

class B {
...
}

이러한 독립적인 두개의 클래스를

class A{
	....
    class B{
    	....
    }
    ....
}

 

이렇게 바꾸면  B는 A의 내부 클래스가 된다.

 

 

내부 클래스의 선언

 

변수가 선언된 위치에 따라 인스턴스 변수, 클래스 변수(static 변수), 지역변수로 나뉘듯 내부클래스도 선언된 위치에 따라 나뉜다. 그리고 각 클래스의 선언 위치에 따라 변수와 동일한 유효범위와 접근성을 갖는다.

 

class Outer{
	class InstanceInner{}
    static class StaticInner{}
    
    void myMethod(){
    	class LocalInner{}
    }
}

https://dsdsds.tistory.com/96

변수에 관해 정리했던 포스팅은 위 링크로...

 

그리고 내부클래스도 클래스이기 때문에 abstract나 final같은 제어자가 사용 가능하며, private, protected도 사용 가능하다.

 

 

 

내부 클래스의 제어자와 접근성

class Sample{
	class InstanceInner{
		int iv = 100;
		//static int cv = 100; ->static변수를 선언할 수 없다.
		final static int CONST = 100; //final static 은 상수이므로 선언 가능하다.
	}
	static class StaticInner{
		int iv = 200;
		static int cv = 200; //static 클래스만 static 멤버를 정의할 수 있다.
	}
	
	void myMethod() {
		class LovalInner{
			int iv = 300;
			//static int cv = 300; ->static 변수 선언 불가
			final static int CONST = 300; //final static 은 상수라서 가능.
		}
	}
	
	public static void main(String[] args) {
		System.out.println(InstanceInner.CONST);
		System.out.println(StaticInner.cv);
	}
}

결과는 

100

200

이다.

 

 

 

내부클래스의 변수 호출

 

1)내부클래스가 인스턴스 클래스인 경우

class Outer{
	class Inner{
		int iv = 100;
	}
}	
class Sample{
	public static void main(String[] args) {
		Outer out = new Outer();
		Outer.Inner in = out.new Inner();
		System.out.println(in.iv);
	}
}

내부 클래스에 있는 iv변수를 호출하려고 한다.

그러려면 먼저 Outer의 인스턴스부터 생성해야 한다. 외부 인스턴스 클래스의 인스턴스가 생성되어야 내부 인스턴스 클래스를 사용할 수 있기 때문이다. 그 뒤 Inner의 인스턴스도 생성한 후 호출한다.

 

 

2)내부클래스가 static 클래스인 경우

class Outer{
	static class Inner{
		int iv = 100;
	}
}	
class Sample{
	public static void main(String[] args) {
		Outer.Inner in = new Outer.Inner();
		System.out.println(in.iv);
	}
}

static 클래스는 외부 클래스의 인스턴스를 생성하지 않고도 사용이 가능하다.