인터페이스
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();
}
}
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
금호 타이어가 굴러갑니다.
금호 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
한국 타이어가 굴러갑니다.
'Java > 8. 인터페이스 (Interface)' 카테고리의 다른 글
Day 11 : 매개 변수의 다형성 (0) | 2021.11.02 |
---|---|
Day 11 : 인터페이스 배열로 구현 객체 관리 (0) | 2021.11.02 |
Day 11 : 자동 타입 변환 (promotion) (0) | 2021.11.02 |
Day 11 : 정적 메소드 사용 (0) | 2021.11.02 |
Day 11 : 디폴트 메소드 사용 (0) | 2021.11.02 |