본문 바로가기

백엔드/자바

상속

반응형

객체지향 프로그램에 장점 중하나인 상속에 대해 알아보자. 상속은 하나의 클래스의 특성과 기능을 물려받고 필요에 따라 상속받는 클래스의 부가적인 특성을 추가하거나 물려받은 특성을 수정하여 사용하는 기능이다. 하나의 클래스는 하나의 부모로부터 상속가능하며 부모다 다른 클래스를 상속하는 경우 조상의 특성은 모두 사용가능하다.

목차

상속구조

모든 클래스는 생성과 동시에 따로 지정하지 않아도 옵젝트 클래스를 상속하며 이외 상속은 extends 키워로 함

상속하기

▶ 부모 클래스

package com.example.inheritencedemo.entities;

public class Vehicle {    
    private String dateProduced;
    private String speed;    

    public String getDateProduced() {
        return dateProduced;
    }

    public void setDateProduced(String dateProduced) {
        this.dateProduced = dateProduced;
    }

    public String getSpeed() {
        return speed;
    }

    public void setSpeed(String speed) {
        this.speed = speed;
    }

    public void move() {
        System.out.println("moving");
    }
}

▶ 자식 클래스

package com.example.inheritencedemo.entities;

public class Car extends Vehicle {
    private String model;
}

아래와 같이 자식클래스에서 부모의 메서드를 활용가능함을 확인 가능

Super()

super()는 자식 클래스에서 부모클래스 생성기를 호출하는 코드로 this()와 비슷한 기능을 함. 둘 다 생성기 내 첫 번째 위치해야 하므로 같이 사용은 불가. 부모 클래스에 매개변수가 있는 생성기만 있는 경우 자식은 반드시 super()를 해당하는 매개변수와 함께 호출해야 한다. 

슈퍼는 생성기를 통해 초기값을 설정할 때 공통되는 값을 부모를 통해 설정하고 자식은 특성에 따라 해당하는 값을 추가 가능하게 한다.

▶ 부모 클래스

package com.example.inheritencedemo.entities;

public class Vehicle {
    private String dateProduced;
    private String speed;

    public Vehicle(String dateProduced, String speed) {
        this.dateProduced = dateProduced;
        this.speed = speed;
    }

    public String getDateProduced() {
        return dateProduced;
    }

    public void setDateProduced(String dateProduced) {
        this.dateProduced = dateProduced;
    }

    public String getSpeed() {
        return speed;
    }

    public void setSpeed(String speed) {
        this.speed = speed;
    }

    public void move() {
        System.out.println("moving");
    }
}

▶ 자식 클래스

package com.example.inheritencedemo.entities;

public class Car extends Vehicle {
    private String model;

    public Car(String model) {
        super("2027", "good");
        this.model = model;
    }
}

덮어쓰기

자식은 부모의 함수를 덮어쓸 수 있다. Ctrl + O 클릭하면 덮어쓰기가 가능한 함수 목록이 표시된다

▶ 자식 클래스

package com.example.inheritencedemo.entities;

public class Car extends Vehicle {
    private String model;

    public Car(String model) {
        super("2027", "good");
        this.model = model;
    }

    @Override
    public void move() {
        super.move();
    }
}

참고로, 부모의 필드를 자식이 직접 접근해야 하는 경우 접근설정 기를 protected로 설정

▶ 부모 클래스

package com.example.inheritencedemo.entities;

public class Vehicle {
    private String dateProduced;
    private String speed;
    protected String type;

    public Vehicle(String dateProduced, String speed) {
        this.dateProduced = dateProduced;
        this.speed = speed;
    }

    public String getDateProduced() {
        return dateProduced;
    }

    public void setDateProduced(String dateProduced) {
        this.dateProduced = dateProduced;
    }

    public String getSpeed() {
        return speed;
    }

    public void setSpeed(String speed) {
        this.speed = speed;
    }

    public void move() {
        System.out.println("moving");
    }
}

▶ 자식 클래스

package com.example.inheritencedemo.entities;

public class Car extends Vehicle {
    private String model;

    public Car(String model) {
        super("2027", "good");
        this.model = model;
    }

    @Override
    public void move() {
        super.move();
        System.out.println(type + model);
    }
}

구성

구성은 상속과 비슷하지만 상속이 부모가 가지는 범주에 속하는 하나의 객체라면 구성은 하나의 클래스의 부속을 나타낸다. 상속보다 코드독립성이 높아 구성을 사용하는 것이 일반적

이상으로 상속에 대해 알아보았다


참고

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html

 

Object (Java SE 17 & JDK 17)

java.lang.Object public class Object Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. Since: 1.0 See Also: Constructor Summary Constructors Method S

docs.oracle.com

 

728x90
반응형

'백엔드 > 자바' 카테고리의 다른 글

함수 오버로딩 VS 오버라이딩  (0) 2023.12.31
자바: 에러: release version 21 not supported  (0) 2023.12.30
클래스  (0) 2023.12.28
스위치  (0) 2023.12.26
스프링 부트 폼  (1) 2023.10.22