Polymorphism

polymorphism(다형성)
polymorphism 이미지 검색결과
ParentClass polymorphism=new ChildClass();
다형성을 이용하여 자식클라스 인스턴스를 부모클라스의 자료형으로 선언할시, 부모클라스의 멤버와 메소드만 사용가능하다.
만일 부모클라스와 자식클라스의 메소드가 동일할 시 가상 메서드의 특성상 상속을 통하여서 오버라이딩 되어 자식클라스의 메소드가 실행된다.
CustomerTest.java
package polymorphism;
public class CustomerTest {
public static void main(String[] args) {
Customer customerLee=new Customer();
customerLee.setCustomerID(10010);
customerLee.setCustomerName("");
customerLee.bonusPoint=1000;
System.out.println(customerLee.showCustomerInfo());
Customer customerKim=new VIPCustomer(10020,"",12345);
customerKim.bonusPoint=1000;
customerKim.bonusPoint=1000;
System.out.println(customerKim.showCustomerInfo());
System.out.println("====== ======");
int price=10000;
int leePrice=customerLee.calcPrice(price);
int kimPrice=customerKim.calcPrice(price);
System.out.println(customerLee.getCustomerName()+""+leePrice+" .");
System.out.println(customerLee.showCustomerInfo());
System.out.println(customerKim.getCustomerName()+""+kimPrice+" .");
System.out.println(customerKim.showCustomerInfo());
}
}
Customer.java
package polymorphism;
public class Customer {
protected int customerID;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public Customer() {
initCustomer();
}
public Customer(int customerID,String customerName) {
this.customerID=customerID;
this.customerName=customerName;
initCustomer();
}
private void initCustomer() {
customerGrade="SILVER";
bonusRatio=0.01;
}
public int calcPrice(int price) {
bonusPoint+=price*bonusRatio;
return price;
}
public String showCustomerInfo() {
return customerName+" "+customerGrade+", "+bonusPoint+".";
}
}
VIPCustomer.java
package polymorphism;
public class VIPCustomer extends Customer {
private int agentID;
double saleRatio;
public VIPCustomer(int customerID,String customerName,int agentID) {
super(customerID,customerName);
customerGrade="VIP";
bonusRatio=0.05;
saleRatio=0.1;
this.agentID=agentID;
}
public int calcPrice(int price) {
bonusPoint+=price*bonusRatio;
return price-(int)(price*saleRatio);
}
public String showCustomerInfo() {
return super.showCustomerInfo()+" "+agentID+"";
}
public int getAgentID() {
return agentID;
}
}