04.再定義方法(上書き)


サブクラスでのメソッドの再定義


  • 上書き:親クラスで定義されたメソッドの実装は、子クラスの実装と一致しません.
    サブクラスで同じ名前のメソッドを再定義できます

  • VIPCustomerクラスのcalcPrice()は割引されていません

  • 再定義と実装が必要
  • VIPCustomer.java
    @Override
    public int calcPrice(int price) {
    	bonusPoint += price * bonusRatio;
    	return price - (int)(price * salesRatio);
    }

    @override Annotation(コメント)


  • コメントの意味

  • コンパイラに特別な情報を提供する役割


  • 宣言子が既存のメソッドと異なる場合、リライト宣言は再定義メソッドとして実行されます.
  • 成形変換とオーバーライド方法の呼び出し


    Customer vc = new VIPCustomer();
    vc変数のタイプはCustomerですが、インスタンスのタイプはVIPCCustomerです.
    Javaは常にインスタンスを呼び出すメソッド(仮想メソッドの原理)
    Javaのすべてのメソッドは仮想メソッドです(virtualmethod)
    CustomerTest.java
    public class CustomerTest {
    
    	public static void main(String[] args) {
    		
    		Customer customerLee = new Customer(10010, "이순신");
    		customerLee.bonusPoint = 1000;
    		System.out.println(customerLee.showCustomerInfo());
    		
    		VIPCustomer customerKim = new VIPCustomer(10020, "김유신");
    		customerKim.bonusPoint = 10000;
    		System.out.println(customerKim.showCustomerInfo());
    		
    		int priceLee = customerLee.calcPrice(10000);
    		int priceKim = customerKim.calcPrice(10000);
    		
    		System.out.println(customerLee.showCustomerInfo() + " 지불금액은 " + priceLee + "원 입니다.");
    		System.out.println(customerKim.showCustomerInfo() + " 지불금액은 " + priceKim + "원 입니다.");
    		
    		Customer customerNo = new VIPCustomer(10030, "나몰라");
    		customerNo.bonusPoint = 10000;
    		int priceNo = customerNo.calcPrice(10000);
    		System.out.println(customerNo.showCustomerInfo() + " 지불금액은 " + priceNo  + "원 입니다.");
    
    	}
    }