상속 (inherit)

제민·2024년 7월 17일

Java 개념 공부

목록 보기
14/21
post-thumbnail

상속이란?

상속은 부모 클래스의 필드와 메소드를 자식 클래스가 그대로 이어받아 사용하는 것을 의미합니다. 상속을 통해 자식 클래스는 부모 클래스의 속성과 기능을 물려받아 코드를 재사용하고 확장할 수 있습니다.

상속의 장점

  1. 코드 재사용성: 적은 양의 코드로 새로운 클래스를 정의하고 사용할 수 있습니다.

  2. 유지보수 용이성: 코드를 공통으로 관리하기 때문에 코드의 추가나 변경이 용이합니다.

상속의 특징

  1. 단일 상속: 자바는 클래스 간의 다중 상속을 지원하지 않으며, 하나의 부모 클래스만 가질 수 있습니다.

  2. 접근 제어: 자식 객체 생성 시에 부모의 필드 값도 전달 받은 경우, 부모 클래스에 정의된 protected 필드는 자식 클래스에서 직접 접근이 가능하지만, private 필드는 접근이 불가능합니다. super() 이용하여 전달받은 부모 필드 값을 부모 생성자 쪽으로 넘겨서 생성하거나 setter, getter 메소드를 이용하여 접근할 수 있습니다.

  3. 메소드 호출: 자식 객체는 부모 클래스에 있는 메소드를 마치 자신의 것처럼 호출할 수 있습니다.

  4. 오버라이딩: 부모 클래스의 정의된 기능이 마음에 들지 않으면 자식 클래스에서 이를 수정할 수 있습니다.

  5. Object 클래스: 모든 클래스는 Object 클래스의 후손이며, Object 클래스에 있는 메소드를 마음대로 호출하거나 오버라이딩할 수 있습니다.

표현식

클래스 간의 상속 시에는 extends 키워드를 사용합니다. 예시에서는 Company 클래스가 부모 클래스고, 이를 상속받는 Academy가 자식 클래스 입니다.

[접근제한자] class 자식클래스명 extends 부모클래스명 {}

ex) public class Academy extends Company {}

단일 상속과 다중 상속

단일 상속(Single Inheritance)
클래스간의 관계가 다중 상속보다 명확하고 신뢰성 있는 코드 작성할 수 있습니다.
자바에서는 다중 상속 미지원하고 단일상속만 지원합니다.

다중 상속(Multiple Inheritance)
C++에서 가능한 기능으로 여러 클래스로부터 상속을 받으며 복합적인 기능을 가진 클래스를 쉽게 작성 가능합니다.
하지만 서로 다른 클래스로부터 상속 받은 멤버 간의 이름이 같은 경우 문제가 발생할 수 있기 때문에 자주 사용하지는 않습니다.

super()

부모 객체의 생성자를 호출하는 메소드로 기본적으로 후손 생성자에 부모 생성자 포함합니다.
후손 객체 생성 시에는 부모부터 생성이 되기 때문에 후손 클래스 생성자 안에는
부모 생성자를 호출하는 super()가 첫 줄에 존재합니다.
(부모 생성자가 가장 먼저 실행되어야 하기 때문에 명시적으로 작성 시에도 반드시 첫 줄에만 작성 가능)
매개변수 있는 부모 생성자 호출은 super(매개변수, 매개변수)를 넣으면 됩니다.

public SubCLS(int i, int j) {
      super(i, j); //부모 객체의 생성자를 호출
      System.out.println("...");
   }

super.

상속을 통한 자식 클래스 정의 시 해당 자식 클래스의 부모 객체를 가리키는 참조변수로, 자식 클래스 내에서 부모 클래스 객체에 접근하여 필드나 메소드 호출 시 사용합니다.

public BusinessMan(String name, String company, String position) {
      super(name); 
      this.company = company;
      this.position = position;
      }

상속 코드 예제

Product 클래스

package h.inherit.ex2;

public class Product {
    private String brand;
    private String pCode;
    private String pName;
    private int price;

    public Product() {
        super();
        System.out.println("Product()");
    }

    public Product(String brand, String pCode, String pName, int price) {
        super();
        this.brand = brand;
        this.pCode = pCode;
        this.pName = pName;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getpCode() {
        return pCode;
    }

    public void setpCode(String pCode) {
        this.pCode = pCode;
    }

    public String getpName() {
        return pName;
    }

    public void setpName(String pName) {
        this.pName = pName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String information() {
        return "브랜드 : " + this.brand + " 제품번호 : " + this.pCode + " 제품이름 : " + this.pName + " 가격 : " + this.price + "원";
    }
}

Desktop 클래스

package h.inherit.ex2;

public class Desktop extends Product {
    private boolean allinOne;

    public Desktop() {
        super();
        System.out.println("Desktop");
    }

    public Desktop(String brand, String pCode, String pName, int price, boolean allinOne) {
        super(brand, pCode, pName, price);
        this.allinOne = allinOne;
    }

    @Override
    public String information() {
        return super.information() + " 올인원 : " + this.allinOne;
    }
}

TV 클래스

package h.inherit.ex2;

public class TV extends Product {
    private int inch;

    public TV() {
        super();
    }

    public TV(String brand, String pCode, String pName, int price, int inch) {
        super(brand, pCode, pName, price);
        this.inch = inch;
    }

    public int getInch() {
        return inch;
    }

    public void setInch(int inch) {
        this.inch = inch;
    }

    @Override
    public String information() {
        return super.information() + " 티비인치 : " + this.inch + "인치";
    }
}

Run 클래스

package h.inherit.ex2;

public class Run {
    public static void main(String[] args) {
        Desktop d1 = new Desktop("lg", "d-100", "사무용PC", 10000000, true);
        System.out.println(d1.information());

        TV tv = new TV("삼성", "s-100", "삼성LED티비", 20000000, 65);
        System.out.println(tv.information());
    }
}

실행 결과

위 예제 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.

Product()
Desktop
브랜드 : lg 제품번호 : d-100 제품이름 : 사무용PC 가격 : 10000000원 올인원 : true
Product()
브랜드 : 삼성 제품번호 : s-100 제품이름 : 삼성LED티비 가격 : 20000000원 >티비인치 : 65인치
profile
초보부터 시작하는 개발자 생활

0개의 댓글