본문으로 바로가기

내부클래스

category 프로그래밍/java 2017. 11. 11. 20:32

내부클래스란?

클래스안에 클래스가 있다는 뜻

여기서는 Monster클래스안에 Brain과 spawn()이라는 클래스가 안에 존재하는 것이다.


public class Monster {

private String name;

public Monster(String name) {

this.name = name;

}

@SuppressWarnings("unused")

private class Brain{

public void think() {

System.out.println(name + " is thinking");

}

}


public void spawn() {

// TODO Auto-generated method stub

Brain brain = new Brain();

brain.think();

}

}



public class Appilcation {


public static void main(String[] args) {

// TODO Auto-generated method stub

Monster mob1 = new Monster("Zombie");

mob1.spawn();

Monster mob2 = new Monster("Skeleton");

mob2.spawn();

}}


실행결과
Zombie is thinking
Skeleton is thinking




내부클래스1 : 중첩클래스 


class InnerExam1{

class Cal{

int value = 0;

public void plus() {

value++;

}

}

}

public class Application {


public static void main(String[] args) {

// TODO Auto-generated method stub

 InnerExam1 t = new InnerExam1();

 InnerExam1.Cal cal =    t.new Cal();

바깥쪽클래스타입 변수 = 객체 생성

 cal.plus();

 System.out.println(cal.value);

}


}



내부클래스2: 정적 중첩클래스 static사용





public class InnerExam2 {

static class Cal{

int value = 0;

public void plus() {

value++;

}

}



public static void main(String[] args) {

// TODO Auto-generated method stub

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) {

// TODO Auto-generated method stub

InnerExam3 t = new InnerExam3();

t.exec();

}


}



'프로그래밍 > java' 카테고리의 다른 글

Enum  (1185) 2017.11.11
java 네트워크  (1212) 2017.09.21
컬렉션  (1214) 2017.09.19
다양한 애플릿  (1212) 2017.09.19
애플릿(애플릿, 애플릿 뷰어)  (1194) 2017.09.16