Java/8. 인터페이스 (Interface)
Day 11 : 필드의 다형성
pancakemaker
2021. 11. 2. 19:06
인터페이스
package sec05.exam01_field_polymorphism;
public interface Tire {
void roll(); //추상 메소드 - public abstract 생략됨. 실행문은 쓰지 않음
}
구현 클래스
package sec05.exam01_field_polymorphism;
public class HankookTire implements Tire {
@Override
public void roll() {
System.out.println("한국 타이어가 굴러갑니다.");
}
}
구현 클래스
package sec05.exam01_field_polymorphism;
public class KumhoTire implements Tire {
@Override
public void roll() {
System.out.println("금호 타이어가 굴러갑니다.");
}
}
필드 다형성
package sec05.exam01_field_polymorphism;
public class Car {
//필드 (Tire interface 타입의 필드)
Tire frontLeftTire = new HankookTire();
Tire frontRightTire = new HankookTire();
Tire backLeftTire = new HankookTire();
Tire backRightTire = new HankookTire();
//메소드
void run() {
frontLeftTire.roll();
frontRightTire.roll();
backLeftTire.roll();
backRightTire.roll();
}
}
필드 다형성 테스트
package sec05.exam01_field_polymorphism;
public class CarExample {
public static void main(String[] args) {
Car myCar = new Car();
myCar.run();
myCar.frontLeftTire = new KumhoTire(); //인터페이스 변수에 KumhoTire 객체 대입
myCar.frontRightTire = new KumhoTire();
myCar.run();
}
}
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
금호 타이어가 굴러갑니다.
금호 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.