[Java] 내부클래스(InnerClass)

Hee·2024년 4월 2일

Java 복습

목록 보기
30/46
post-thumbnail

내부클래스

내부클래스란 클래스 안에 선언된 클래스이다.


어느 위치에 선언하느냐에 따라 4가지 형태가 있다.

1 중첩클래스, 인스턴스 클래스
필드(=인스턴스 변수)를 선언하는 위치에 클래스 선언된 경우

  • 내부에 있는 Cal 객체를 생성하기 위해서는 밖에 있는 InnerExam1의 객체를 먼저 만든 후에, InnerExam1.Cal cal = t.new Cal();과 같은 방법으로 Cal 객체를 생성한 후 사용한다.
public class InnerExam1{
	Class Cal{
    	int value = 0;
        public void plus(){
        	value++;
        }
    }
    
    public static void main(String[] args){
    	InnerExam1 t = new InnerExam1();
        InnerExam1.Cal cal = t.new Cal();
        cal.plus();
        System.out.println(cal.value);
    }
}

2 정적 중첩 클래스, static 클래스
내부클래스가 static으로 정의된 경우

  • 필드 선언할 때 static한 필드로 선언한 것과 같다. 해당 경우에는 InnerExam2 객체를 따로 생성할 필요 없이 new InnerExam2.Cal() 로 객체 생성이 가능하다.
public class InnerExam2{
	static class Cal{
    	int value = 0;
        public void plus(){
        	value++;
        }
    }


    public static void main(String[] args){
        InnerExam2.Cal cal = new InnerExam2.Cal();
        cal.plus();
        System.out.println(cal.value);
    }
}

3 지역 중첩 클래스, 지역 클래스
메소드 안에 클래스를 선언한 경우

  • 메소드 안에서 해당 클래스를 이용할 수 있다.
public class InnerExam3{
	public void exec(){
    	class Cal{
        	int value = 0;
            public void plus(){
            	value++;
            }
        }
        Cal cal = new Cal();
        cal.plus();
        System.out.println(cal.value);
    }
    
    public static void main(String[] args){
    	InnerExam3 t = new InnerExam3();
        t.exec();
    }
}

네 번째로는 익명클래스가 있다. 익명클래스는 다음 포스팅에서 따로!

0개의 댓글