๊ด€๋ฆฌ ๋ฉ”๋‰ด

โœ๐Ÿป๊ธฐ๋กํ•˜๋Š” ๋ธ”๋กœ๊ทธ

[ JAVA ] ์ƒ์† ๋ณธ๋ฌธ

Language/Java

[ JAVA ] ์ƒ์†

์ฉ์‹œํ‚ด 2020. 11. 15. 15:11
728x90

์ƒ์†

ํด๋ž˜์Šค๋ฅผ ์ •์˜ํ•  ๋•Œ ๊ธฐ์กด์— ๊ตฌํ˜„๋œ ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›์•„์„œ ์†์„ฑ (๋ณ€์ˆ˜), ๊ธฐ๋Šฅ(๋ฉ”์†Œ๋“œ)๊ฐ€ ํ™•์žฅ๋˜๋Š” ๊ฒƒ

๊ธฐ์กด์˜ ํด๋ž˜์Šค๋ฅผ ๊ฐ€์ ธ๋‹ค๊ฐ€ ์กฐ๊ธˆ ๋” ํ™•์žฅ์˜ ๊ฐœ๋…, ์ด์งˆ์ ์ธ ํด๋ž˜์Šค ๋ผ๋ฆฌ๋Š” ์ƒ์†์ด ์ผ์–ด๋‚˜์ง€ ์•Š์Œ

 

a class ← b class

bํด๋ž˜์Šค๊ฐ€ aํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š”๋‹ค. ๋‹จ์ผ ์ƒ์†๋งŒ ๊ฐ€๋Šฅ

์ƒ์†์€ ์ฝ”๋“œ์˜ ์žฌ์‚ฌ์šฉ์ด ์•„๋‹˜

์ƒ์†๋ฐ›๋Š” ํด๋ž˜์Šค๋ฅผ ํ™”์‚ดํ‘œ๋กœ ๊ฐ€๋ฆฌํ‚ด

 

์˜ˆ์ œ) ๊ณ ๊ฐ๊ด€๋ฆฌ ํ”„๋กœ๊ทธ๋žจ

๊ณ ๊ฐ ์ค‘์—๋Š” ์ผ๋ฐ˜ ๊ณ ๊ฐ customer, ๋‹จ๊ณจ ๊ณ ๊ฐ vipCustomer๊ฐ€ ์žˆ๋‹ค. 

vipCustomer : ์ผ๋ฐ˜ ๊ณ ๊ฐ๊ณผ ์†์„ฑ์€ ์œ ์‚ฌํ•˜์ง€๋งŒ ๋” ๋งŽ์€ ํ˜œํƒ์„ ๊ฐ€์ง€๊ฒŒ ๋จ

์˜ˆ ) ์ œํ’ˆ ๊ตฌ๋งค ์‹œ 10% ํ• ์ธ

      ๋ณด๋„ˆ์Šค ํฌ์ธํŠธ 5%

      ๋‹ด๋‹น ์ƒ๋‹ด์› ๋ฐฐ์ •

์ฐธ์กฐ )java ์›น ๊ฐœ๋ฐœ ๋งˆ์Šคํ„ฐ ์˜ฌ์ธ์› ํŒจํ‚ค์ง€ 

์ƒ์†๋ฐ›์„ Customer ํด๋ž˜์Šค 

๋ณ€์ˆ˜ ์ ‘๊ทผ ์ œํ•œ์ž๋ฅผ ๋ณด๋ฉด protected๋กœ ์„ ์–ธ์ด ๋˜์–ด์žˆ๋‹ค. protected๋Š” ์™ธ๋ถ€ ํด๋ž˜์Šค์—์„œ๋Š” ์ ‘๊ทผ์ด ๋ถˆ๊ฐ€ ํ•˜์ง€๋งŒ, ์ƒ์†๋ฐ›์€ ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ๋Š” ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ protected๋กœ ์„ ์–ธ๋˜์—ˆ๋‹ค.

 

package inheritance;

public class Customer {
    protected int customerID; //String null๋กœ ์ดˆ๊ธฐํ™”
    protected String customerName;
    protected String customerGrade;
    int bonusPoint;  //int 0์œผ๋กœ ์ดˆ๊ธฐํ™”
    double bonusRatio;

    public Customer(){
        customerGrade = "SILVER";
        bonusRatio = 0.01;
    }

    public int calPrice(int price){
        bonusPoint += price * bonusRatio;
        return price;
    }

    public String showCustomerInfo(){
        return customerName+"๋‹˜์˜ ๋“ฑ๊ธ‰์€"+customerGrade+"๋ณด๋„ˆ์Šค ํฌ์ธํŠธ๋Š” "+bonusPoint+"์  ์ž…๋‹ˆ๋‹ค.";
    }

    public int getCustomerID() {
        return customerID;
    }

    public String getCustomerName() {
        return customerName;
    }

    public String getCustomerGrade() {
        return customerGrade;
    }

    public void setCustomerID(int customerID) {
        this.customerID = customerID;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public void setCustomerGrade(String customerGrade) {
        this.customerGrade = customerGrade;
    }

}

 

customerํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›์€ vipCustomer ํด๋ž˜์Šค

customer ํด๋ž˜์Šค์—์„œ ์ •์˜๋œ ๊ธฐ๋Šฅ์€ vipCustomer ํด๋ž˜์Šค์—์„œ๋„ ๋™์ผํ•˜๊ฒŒ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. vipCustomerํด๋ž˜์Šค์—์„œ๋งŒ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ์ถ”๊ฐ€์ ์ธ ๋ณ€์ˆ˜ ์„ ์–ธ์ด๋‚˜ ๋ฉ”์„œ๋“œ๊ฐ€ ์„ ์–ธ๋˜์–ด์•ผ ํ•œ๋‹ค. 

package inheritance;

public class VIPCustomer extends Customer {
    //vipcustomer ํด๋ž˜์Šค์—์„œ ์ถ”๊ฐ€๋œ ๋ณ€์ˆ˜
    double salesRatio;
    private int agentId;

    public VIPCustomer(){
        customerGrade = "VIP";
        bonusRatio = 0.05;
    }
}
728x90
๋ฐ˜์‘ํ˜•