Programming Language/Java

상속을 이용하기 전후를 비교해보기

Ma_Sand 2022. 3. 6. 17:14
반응형

[상속 받기 전]

// 클래스 Banana
// 필드
public class Banana {
    private String nation;
    private int price;
    private String retailer;
    private boolean yellow;

    // 생성자
    public Banana() {  // 기본 생성자

    }
    public Banana(String nation, int price, String retailer, boolean yellow) {
        this.nation = nation;
        this.price = price;
        this.retailer = retailer;    // 자신의 클래스 내에 있으므로 참조변수 this. 를 사용
       this.yellow = yellow;
    }
    // 메소드
    // getter / setter 메소드 사용하여 값을 입력하고 가져오기
    public String getNation() {  // nation
        return nation;
    }
    public void setNation(String nation) {
        this.nation = nation;
    }
    public int getPrice() {  // price
        return Price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getRetailer() {  // retailer
        return retailer;
    }
    public void setRetailer(String retailer) {
        this.retailer = retailer;
    }
    public String getYellow() {  // yellow
        return yellow;
    }
    public void setYellow(boolean yellow) {
        this.yellow = yellow;
    }
    // 문자열로 info 메소드를 생성하여 전부를 받기
    public String info() {
        return "바나나의 원산지는 " + nation + ", 가격은 " + price + "원, 판매처는 " 
               + retailer + ", 색깔은 노란색? " + yellow;
    }
}



// 클래스 Apple
public class Apple {
    private String nation;
    private int price;
    private String retailer;
    private String round;

    public Apple() { 

    }
    public Apple(String nation, int price, String retailer, String round) {
        this.nation = nation;
        this.price = price;
        this.retailer = retailer;
        this.round = round;
    }

    public String getNation() {  // nation
        return nation;
    }
    public void setNation(String nation) {
        this.nation = nation;
    }
    public int getPrice() {  // price
        return Price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getRetailer() {  // retailer
        return retailer;
    }
    public void setRetailer(String retailer) {
        this.retailer = retailer;
    }
    public String getRound() {  // round
        return round;
    }
    public void setRound(String round) {
        this.round = round;
    }

    public String info() {
        return "사과의 원산지는 " + nation + ", 가격은 " + price + "원, 판매처는 " 
               + retailer + ", 모양은 " + round;
    }
}



// 클래스 Banana와 Apple을 실행시킬 클래스 BeforeRun
public class BeforeRun {
    public static void main(String[] args) {
        Banana b = new Banana("필리핀",3500 , "이마트", true);
        Apple a = new Apple("안동", 2000, "홈플러스", "둥글다");
        
        System.out.println(b.info());
        System.out.println(a.info());
    }
}

▼실행결과

바나나의 원산지는 필리핀, 가격은  3500, 판매처는 이마트, 색깔은 노란색? true
사과의 원산지는 안동, 가격은 2000원, 판매처는 홈플러스, 모양은 둥글다

 

클래스 Banana와 Apple의 공통적인 필드, 메소드가 있다.

<nation, price, retailer> 이 세 가지.

클래스가 몇 개 안될 때는 이렇게 하나하나 다 적어도 상관은 없지만, 클래스의 수가 늘어날 수록 관리하기가 매우 힘들어질 것이다. 이럴 때 사용하는 것이 상속이다.

바나나와 사과의 공통분모는 과일이므로 부모 클래스명을 Fruit로 하고, 이 부모 클래스에다가 중복된 부분들을 모아서 작성하면 관리하기가 훨씬 쉬워진다.

 

 

[상속 받은 후]

// 부모 클래스 Fruit
// 필드
public class Fruit {  // 중복 필드 모아서 적기
    private String nation;
    private int price;
    private String retailer;

    // 생성자
    public Fruit() {  // 기본 생성자
   
    }
    public Fruit(String nation, int price, String retailer) {
        this.nation = nation;
        this.price = price;
        this.retailer = retailer;   // 해당 클래스 내에 있는 필드를 초기화하였으므로 this. 사용
    }
    // 메소드
    public String getNation() {   // 공통 메소드 한데 모아 적기
        return nation;
    }
    public void setNation(String nation) {
        this.nation = nation;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getRetailer() {
        return retailer;
    }
    public void setRetailer(String retailer) {
        this.retailer = retailer;
    }
    // 문자열 String으로 공통된 매개변수들 전부 적기
    public String info() {
        return "원산지: " + nation + ", 가격: " + price + "원, 판매처: " + retailer;
    }
}



// 자식 클래스 Banana
public class Banana {  // Apple과의 공통 필드를 제외한 Banana만의 필드
    private boolean yellow;

    public Banana() {  // 기본 생성자

    }
    public Banana(String nation, int price, String retailer, boolean yellow) {
        super(nation, price, retailer);  // 메소드 super()를 이용하여 부모 메소드 호출하기
        this.yellow = yellow;
    }
    public boolean getYellow() {  // nation, price, retailer는 부모 클래스에서
        return yellow;            // 이미 작성하였으므로 yellow만 적으면 된다.
    }
    public void setYellow(boolean yellow) {
        this.yellow = yellow;
    }

    @Override   // 부모 메소드를 변경할 때 오버라이딩.
    public String info() {
        return "원산지: " + nation + ", 가격: " + price + "원, 판매처: " + retailer 
               + "색깔이 노랑색?" + yellow;
    }
}



// 자식 클래스 Apple
public class Apple {
    private String round;

    public Apple() {

    }
    public Apple(String nation, int price, String retailer, String round) {
        super(nation, price, retailer);
        this.round = round;
    }
    public String getRound() {
        return round;
    }
    public void setRound(String round) {
        this.round = round;
    }
    @Override
    public String info() {
        return "원산지: " + nation + ", 가격: " + price + "원, 판매처: " + retailer 
               + ", 모양: " + round;
    }
}



// 클래스들을 실행시킬 클래스 FruitRun
public class FruitRun {
    public static void main(String[] args) {  // Banana, Apple 메소드 호출
        Banana b = new Banana("필리핀", 3500, "이마트", true);
        Apple a = new Apple("안동", 2000, "홈플러스", "둥글다");
        
        System.out.println(b.info());  // 출력 메소드
        System.our.println(a.info());
    }
}

▼실행결과

원산지: 필리핀, 가격: 3500원, 판매처: 이마트, 색깔이 노랑색? true
원산지: 안동, 가격: 2000원, 판매처: 홈플러스, 모양: 둥글다

 

상속을 사용하니 전보다 코드가 훨씬 간결해졌다.

부모 메소드를 자식 클래스로 호출할 때 super() 메소드를 사용하면 좋다. 참조변수 super. 도 있긴 한데 이건 this. 처럼 일일이 적어줘야 해서 깔끔하게 super()를 사용하는 게 더 낫다.

반응형