자바_기초
다형성 : 하나의 참조변수로 여러 타입의 객체를 참조할 수 있는 것
잠수콩
2019. 5. 27. 14:43
// 다형성
// - 여러가지 형태를 가질 수 있는 능력
// - 하나의 참조변수로 여러 타입의 객체를 참조할 수 있는 것
// 기본조건 : 상속! + interface
//아래 A, B, C의 상위는 Object. Object를 자동 상속한다.
class A{
A(){
System.out.println("A 클래스");
}
void info() {
System.out.println("A 메서드");
}
}
class B{
B(){
System.out.println("B 클래스");
}
void info() {
System.out.println("B 메서드");
}
}
class C{
C(){
System.out.println("C 클래스");
}
void info() { //메서드
System.out.println("C 메서드");
}
}
public class PolymorphismEx {
public static void main(String[] args) {
Object a1 = new A();
Object b1 = new B();
Object c1 = new C();
System.out.println("===================");
// 부모 참조 변수로 자식객체를 생성하면
// 부모가 물려준 메서드, 변수 밖에 접근 못함
// 자식메서드, 변수에 접근이 불가능
Object a3 = new A();
// a3.info(); //접근불가능
System.out.println("===================");
B a2 = new B();
System.out.println("===================");
a2.info(); //접근 가능
System.out.println("===================");
}
}