컴파일 타임 다형성(정적 다형성, Compile-Time)
런타임 다형성(동적 다형성, Runtime)
package section12.ex01;
public interface I {
abstract void printClassName();
}
package section12.ex01;
public class A implements I {
@Override
public void printClassName() {
System.out.println("A클래스");
}
}
package section12.ex01;
public class B implements I {
@Override
public void printClassName() {
System.out.println("B클래스");
}
}
package section12.ex01;
public class C implements I {
@Override
public void printClassName() {
System.out.println("C클래스");
}
}
package section12.ex01;
public class Ex1201 {
public static void main(String[] args) {
I a = new A();
I b = new B();
I c = new C();
a.printClassName();
b.printClassName();
c.printClassName();
}
}
package section12.ex02;
// 기본 Vehicle 클래스
class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
void stop() {
System.out.println("Vehicle is stopping");
}
}
// Car 클래스는 Vehicle 클래스를 상속받음
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting");
}
@Override
void stop() {
System.out.println("Car is stopping");
}
}
// Bike 클래스는 Vehicle 클래스를 상속받음
class Bike extends Vehicle {
@Override
void start() {
System.out.println("Bike is starting");
}
@Override
void stop() {
System.out.println("Bike is stopping");
}
}
// 메인 클래스
public class Ex1202 {
public static void main(String[] args) {
Vehicle myCar = new Car(); // 업캐스팅
Vehicle myBike = new Bike(); // 업캐스팅
myCar.start(); // Car is starting
myCar.stop(); // Car is stopping
myBike.start(); // Bike is starting
myBike.stop(); // Bike is stopping
}
}