Overriding
25 Aug 2021 -
1 minute read
- Overriding(μ€λ²λΌμ΄λ©)
-
μμν΄λμ€μ μ μλ λ©μλμ ꡬν λ΄μ©μ΄ νμ ν΄λμ€μμ ꡬνν λ΄μ©κ³Ό λ§μ§ μμ κ²½μ° νμν΄λμ€μμ λμΌν μ΄λ¦μ λ©μλλ₯Ό μ¬μ μ
-
@overriding annotation = μ¬μ μλ λ©μλ
-
ex)
-
Customer.java
public class Customer { protected String customerName; protected String customerGrade; int bonusPoint; double bonusRatio; //ν¬μΈνΈ μ 립λ₯ public Customer(String customerName) { this.customerName = customerName; customerGrade = "SILVER"; bonusRatio = 0.01; } public int calcPrice(int price) { bonusPoint += price * bonusRatio; //ꡬ맀 κ°κ²©μ *0.01 λ§νΌ ν¬μΈνΈ μ 립 return price; } public String showCustomerInfo() { return customerName + "λμ λ±κΈμ " + customerGrade + "μ΄λ©°, 보λμ€ ν¬μΈνΈλ " + bonusPoint + " μ μ λλ€."; } }
-
VIPCustomer.java
public class VIPCustomer extends Customer{ double salesRatio; //ν μΈλ₯ public VIPCustomer(String customerName) { super(customerName); customerGrade = "VIP"; bonusRatio = 0.05; salesRatio = 0.1; } @Override //μν κ°κ²© ν μΈ > calcPrice λ©μλ μ€λ²λΌμ΄λ©-μ¬μ μ public int calcPrice(int price) { // return super.calcPrice(price); // //μλ μλ ꡬν κ·Έλλ‘ λ°ν bonusPoint += price * bonusRatio; price -= (int)(price * salesRatio); return price; } public String showCustomerInfo() { return customerName + "λμ λ±κΈμ " + customerGrade + "μ΄λ©°, 보λμ€ ν¬μΈνΈλ " + bonusPoint + " μ μ λλ€."; } }
-
Main.java
public class Main { public static void main(String[] args) { Customer customerA = new Customer("λ°νλ"); customerA.bonusPoint = 1000; int price = customerA.calcPrice(30000); System.out.println(customerA.showCustomerInfo()); System.out.println("μ§λΆνμ€ κΈμ‘μ " + price + "μ μ λλ€."); VIPCustomer customerB = new VIPCustomer("κΉλ°λ€"); customerB.bonusPoint = 15000; price = customerB.calcPrice(30000); System.out.println(customerB.showCustomerInfo()); System.out.println("μ§λΆνμ€ κΈμ‘μ " + price + "μ μ λλ€."); } }
-
μΆλ ₯κ²°κ³Ό
-
-