다형성이란 한 타입의 참조변수를 통해 여려 타입의 객체를 잠조할 수 있도록 만든 것을 의미한다.
상위 클래스 타입의 참조변수를 통해 하위 클래스의 객체를 참조 할 수 있도록 허용해 준것이다.
class Vehicle{
void run(){
System,out.println("달립니다.");
}
class Car extends Vehicle{
void run(){
System,out.println("달립니다.");
}
class Test{
public static void main(String[] args) {
Car car = new Car();
**Vehicle car2 = new Car();**
}
Vehicle car2 = new Car();
처럼 상위 클래스인 Vehicle을 참조하여 하위 클래스의 객체를 만들 수 있다.
단, 반대로 Car car3 = new Vehicle();
처럼 반대로 하위 클래스를 참조변수로 하여 상위클래스의 객체를 만들 수 없다.
아래는 다형성을 활용한 예시이다.
class Coffee{
int price;
Coffee(int price) {
this.price = price;
}
}
class Americano extends Coffee{
Americano() {
super(4000);
}
}
class Latte extends Coffee{
Latte() {
super(4000);
}
}
class Customer{
int money = 10000;
void calc(Coffee coffee){
money -= coffee.price;
System.out.println("거스름돈 : "+money);
}
}
void calc(Latte latte){
void calc(Americano americano){
처럼 일일히 만들지 않고
oid calc(Coffee coffee){
만 메서드 만든 다음
public static void main(String[] args) {
Coffee americano = new Americano();
Coffee latte = new Latte();
Customer customer = new Customer();
customer.calc(americano);
customer.calc(latte);
}
이런식으로 하면 된다.
~~Coffee americano = new Americano();
Coffee latte = new Latte();~~
Customer customer = new Customer();
customer.calc(new Americano());
customer.calc(new Latte());
이렇게 더 줄일 수도 있다.