본문 바로가기

자바/클래스

내부클래스

예제1)


public class Test1 {

public static void main(String[] args) {

Demo1 aa=new Demo1(); //객체생성=> 메모리 할당.

// Demo1.Ex1 bb=new Demo1.Ex1();

Demo1.Ex1 bb=aa.new Ex1(); // 내부클래스의 객체생성.

bb.write();

}

}


class Demo1{

public static int a=10;

public int b=20;

// 내부 클래스

public class Ex1 {

public int c;

public void write() {

System.out.println(a+":"+b+":"+c);

}

}

public void test() {

Ex1 oo=new Ex1();

oo.write();

}

public void sample(){

int x=30;

final int y=50;

class Sam1 { //메서드안의 내부클래스

public void sub(){

//로컬변수는 final만 접근가능

// System.out.println(a+":"+b+":"+":"+x);

System.out.println(a+":"+b+y);

}

}

Sam1 ss=new Sam1();

ss.sub();

}

}


예제1 결과)

10:20:0

=======================================================================================================================

예제2)

public class Test2 {
public static void main(String[] args) {
Demo2.Ex2 bb=new Demo2.Ex2();
bb.write();
Demo2 aa=new Demo2();       //외부클래스 객체 생성
// Demo2.Ex2 cc=aa.new Ex2(); // 에러. 외부객체로는 생성불가 (보안적인부분에서 유리)
}
}

class Demo2{
static int a=10;
int b=20;
//중첩 static 클래스
//안드로이드의 대부분의 클래스가 static class로 이루어짐
public static class Ex2{
int c=30;
public void write(){
//외부 멤버는 static만 접근 가능
// System.out.println(a+":"+b+":"+":"+c); //에러
System.out.println(a+":"+c);
}
}
public void test(){
//중첩 클래스 객체 생성
Ex2 oo=new Ex2();
oo.write();
}
}

예제2 결과)

10:30

'자바 > 클래스' 카테고리의 다른 글

anonymous class 익명클래스  (0) 2013.05.21
인터페이스 interface  (0) 2013.05.21
abstract 클래스  (0) 2013.05.21
상속 super  (0) 2013.05.21
Scanner 클래스  (0) 2013.05.19