class Parent{
...
}
class Child extends Parent{
...
}
Parent pa = new Parent();
Child ch = new Child();
Parent pc = new Child();
Child cp = new Parent(); // 오류
참조 변수의 타입 변환
(변환할타입의클래스이름) 변환할참조변수
class Parent { ... }
class Child extends Parent { ... }
class Brother extends Parent { ... }
Parent pa01 = null;
Child ch = new Child();
Parent pa02 = new Parent();
Brother br = null;
pa01 = ch; // pa01 = (Parent)ch; 와 같으며, 타입 변환을 생략할 수 있음.
br = (Brother)pa02; // 타입 변환을 생략할 수 없음.
br = (Brother)ch; // 직접적인 상속 관계가 아니므로, 오류 발생.
public class Polymorphism{
public static void main(String[] args) {
Parent p = new Parent();
System.out.println(p instanceof Object); // true
System.out.println(p instanceof Parent); // true
System.out.println(p instanceof Child); // false
}
}
abstract class 클래스이름{
...
abstract 반환타입 메서드이름();
...
}
abstract class Animal { abstract void cry(); }
class Cat extends Animal { void cry() { System.out.println("냐옹냐옹!"); } }
class Dog extends Animal { void cry() { System.out.println("멍멍!"); } }
public class Polymorphism02 {
public static void main(String[] args) {
// Animal a = new Animal();
// 추상 클래스는 인스턴스를 생성할 수 없음.
Cat c = new Cat();
Dog d = new Dog();
c.cry();
d.cry();
}
}
// 결과
냐옹냐옹!
멍멍!
접근제어자 interface 인터페이스이름 {
...
}
class 클래스이름 implements 인터페이스이름{
...
}
interface Animal { public abstract void cry(); }
class Cat implements Animal {
public void cry() {
System.out.println("냐옹냐옹!");
}
}
class Dog implements Animal {
public void cry() {
System.out.println("멍멍!");
}
}
public class Polymorphism03 {
public static void main(String[] args) {
Cat c = new Cat();
Dog d = new Dog();
c.cry();
d.cry();
}
}
// 결과
냐옹냐옹!
멍멍!
Taxi 인터페이스
TaxiDriver 클래스
volvo 클래스
bmw 클래스
sonata 클래스
work 클래스