μμ
24 Aug 2021 -
1 minute read
-
μ΄λ―Έ ꡬνλ ν΄λμ€λ₯Ό μμ(inheritance) λ°μ μμ±μ΄λ κΈ°λ₯μ νμ₯νμ¬ ν΄λμ€λ₯Ό ꡬν
-
μ΄λ―Έ ꡬνλ ν΄λμ€λ³΄λ€ λ ꡬ체μ μΈ κΈ°λ₯μ κ°μ§ ν΄λμ€λ₯Ό ꡬνν΄μΌ ν λ κΈ°μ‘΄ ν΄λμ€ μμ
-
class B extends A{}
: Bν΄λμ€κ° Aν΄λμ€λ₯Ό μμλ°μ -
λ¨μΌ μμ(single inheritance) : extends ν€μλ λ€μλ λ¨ νλμ ν΄λμ€λ§μ΄ μ¬ μ μμ
-
- μμ ν΄λμ€λ νμ ν΄λμ€λ³΄λ€ λ μΌλ°μ μΈ κ°λ κ³Ό κΈ°λ₯
- νμ ν΄λμ€λ μμ ν΄λμ€λ³΄λ€ λ ꡬ체μ μΈ κ°λ κ³Ό κΈ°λ₯
- νμ ν΄λμ€κ° μμ ν΄λμ€μ μμ±κ³Ό κΈ°λ₯μ νμ₯(extends)
- ex)
-
Customer.java
public class Customer { //νμν΄λμ€μμ μ κ·Όν μ μλλ‘ protected protected String customerName; protected String customerGrade; int bonusPoint; double bonusRatio; public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerGrade() { return customerGrade; } public void setCustomerGrade(String customerGrade) { this.customerGrade = customerGrade; } public Customer() { customerGrade = "SILVER"; bonusRatio = 0.01; } public String showCustomerInfo() { return customerName + "λμ λ±κΈμ " + customerGrade + "μ΄λ©°, 보λμ€ ν¬μΈνΈλ " + bonusPoint + "μ μ λλ€."; } }
-
VIPCustomer.java
public class VIPCustomer extends Customer{ double salesRatio; //ν μΈμ¨ private String agentId; //λ΄λΉ μλ΄μ public String getAgentId() { return agentId; } public void setAgentId(String agentId) { this.agentId = agentId; } public VIPCustomer() { customerGrade = "VIP"; bonusRatio = 0.05; salesRatio = 0.1; } }
-
Main.java
public class Main { public static void main(String[] args) { Customer customerA = new Customer(); customerA.setCustomerName("λ°νλ"); customerA.bonusPoint = 1000; System.out.println(customerA.showCustomerInfo()); VIPCustomer customerB = new VIPCustomer(); customerB.setCustomerName("κΉλ°λ€"); customerB.bonusPoint = 15000; System.out.println(customerB.showCustomerInfo()); //Customerν΄λμ€ μ λ©μλμ΄μ§λ§ μμ λ°μ μ¬μ© κ°λ₯ } }
-
μΆλ ₯κ²°κ³Ό
-