자바 상속

조항주·2022년 4월 26일

study

목록 보기
5/20
post-thumbnail

상속

상속의 정의와 장점

상속이란 기존의 클래스를 재사용하여 새로운 클래스를 작성하는 것이다. 이러한 특징은 코드의 재사용성을 높이고 코드의 중복을 제거하여 프로그램의 생산성과 유지보수에 크게 기여한다
상속 구현할 때는 extends 키워드를 사용

조상클래스 부모(parent)클래스, 상위(super)클래스, 기반(base)클래스
자손클래스 자식(child)클래스, 하위(sub)클래스, 파생된(derived)클래스

public class Tv {
    boolean power;
    int channel;

    void power() {
        this.power = !this.power;
    }
    void channelUp() {
        ++this.channel;
    }
    void channelDown() {
        --this.channel;
    }
}
public class CaptionTv extends Tv {
    boolean caption;

    public CaptionTv(boolean caption) {
        this.caption = caption;
    }

    void displayCaption(String text) {
        if (this.caption) {
            System.out.println(text);
        }
    }
}

생성자와 초기화 블럭은 상속되지 않는다. 멤버만 상속된다.
자손 클래스의 멤버 개수는 조상 클래스보다 항상 같거나 많다.

클래스간의 관계 포함관계

상속이외에도 클래스간의 관계를 맺어주고 클래스를 재사용하는 방법

public class Point {
    int y;
    int x;
}
public class Circle {
    int y;
    int x;
    int r;
}
public class Circle {
    Point p;
    int r;
}

생각해보자~~

상속 받으면 부모자식간에 형변환이 가능할까

public class Main {

    public static void main(String[] args) {
        Tv captionTv = new CaptionTv(true);
        CaptionTv tv = new Tv();
    }
}

0개의 댓글