728x90
문제
아래 3개의 클래스를 작성하고, 실행 결과를 출력하시오! (익명 구현 객체)
Student, StudentAnonymous, StudentExample
Student(조상 클래스)
멤버 변수
String name
멤버 함수
public void wake() *출력결과 보고 구현
StudentAnonymous(익명 자식 객체를 만들 클래스)
멤버 변수
Student field
*필드의 익명 자식 클래스 생성 (goSchool 메서드 구현, * 조상의 wake 오버라이딩)
멤버 함수
void method1()
* 로컬 변수의 초기값으로 자식 객체 생성 후 goMoving메서드, wake 오버라이딩
void method2(Student student)
goStudy메서드, wake오버라이딩
StudentExample(실행클래스)
결과
*필드(멤버변수)의 초기값으로 생성된 자식객체
신상민이 6시에 일어납니다.
신상민이 등교합니다.
*로컬변수의 초기값으로 생성된 자식 객체
윤대현이 9시에 일어납니다.
윤대현이 영화를 보러 갑니다.
*매개변수의 매개값으로 익명 자손 객체를 생성
김수현이 4시에 일어납니다.
김수현이 공부합니다.
코드
class Student1 {
String name;
/*
public Student(String name) {
this.name = name;
}
*/
public void wake() {
}
}
class StudentAnonymous {
Student1 field = new Student1() {
public void wake() {
System.out.println("신상민이 6시에 일어납니다.");
goSchool();
System.out.println();
}
public void goSchool() {
System.out.println("신상민이 등교합니다.");
}
};
void method1() {
Student1 field = new Student1() {
public void wake() {
System.out.println("윤대현이 9시에 일어납니다.");
goMoving();
System.out.println();
}
public void goMoving() {
System.out.println("윤대현이 영화를 보러 갑니다.");
}
};
field.wake();
}
void method2(Student1 student) {
student.wake();
}
}
class StudentExample {
public static void main(String[] args) {
StudentAnonymous sa = new StudentAnonymous();
sa.field.wake();
//sa.field.goSchool(); 안된다. goSchool은 student한테 없음
sa.method1();
sa.method2(new Student1() {
public void wake() {
System.out.println("김수현이 4시에 일어납니다.");
goStudy();
System.out.println();
}
public void goStudy() {
System.out.println("김수현이 공부합니다.");
}
});
}
}
원래 클래스가 어떤 메소드를 가질 수 있는지 보고, 사용할 수 있는지 판단.
생성자 활용해서 만들기
class Student1 {
String name;
public Student1(String name) {
this.name = name;
}
public void wake() {
}
}
class StudentAnonymous {
Student1 field = new Student1("신상민") {
public void wake() {
System.out.println(name + "이 6시에 일어납니다.");
goSchool();
System.out.println();
}
public void goSchool() {
System.out.println(name + "이 등교합니다.");
}
};
void method1() {
Student1 field = new Student1("윤대현") {
public void wake() {
System.out.println(name + "이 9시에 일어납니다.");
goMoving();
System.out.println();
}
public void goMoving() {
System.out.println(name + "이 영화를 보러 갑니다.");
}
};
field.wake();
}
void method2(Student1 student) {
student.wake();
}
}
class StudentExample {
public static void main(String[] args) {
StudentAnonymous sa = new StudentAnonymous();
sa.field.wake();
// sa.field.goSchool(); 안된다. goSchool은 student한테 없음
sa.method1();
sa.method2(new Student1("김수현") {
public void wake() {
System.out.println(name + "이 4시에 일어납니다.");
goStudy();
System.out.println();
}
public void goStudy() {
System.out.println(name + "이 공부합니다.");
}
});
}
}728x90
'Java' 카테고리의 다른 글
| [Java] 컬렉션과 제네릭 예제 (Vector,ArrayList,HashMap) (0) | 2023.09.02 |
|---|---|
| [Java] (interface 익명 구현 객체) (19-3) (0) | 2023.09.01 |
| [Java] (interface 익명 구현 객체) (19-1) (0) | 2023.08.31 |
| [Java] (interface 익명 구현 객체) (0) | 2023.08.31 |
| [Java] (interface) (18-2) (0) | 2023.08.31 |