상속 - extends (+ 생성자 오버로딩)

김민영·2023년 1월 22일
0

Java

목록 보기
8/14
  • class를 상속받는 방법

개념

  • 상속 : 부모 클래스의 기능을 확장한다.
  • 자식은 부모 클래스의 메소드를 사용할 수 있다.
  • extends를 사용하면 오버라이딩 없이 부모에 구현되어있는 것을 사용할 수 있다.
  • 부모에게 없는, 자식만의 멤버 변수 또는 멤버 메소드를 지정할 수 있다.
  • 부모클래스의 멤버 메소드와 같은 이름의 메소드를 자식클래스에서 지정하면 오버라이딩하게 된다.
    • 메소드 오버라이딩에 관한 것은 하위 기술.
    • 메소드 오버라이딩: 부모 클래스의 메소드를 자식 클래스에서 재정의해서 사용하는 것
      • 부모 클래스의 메소드 무시, 덮어쓰기
    • 오버라이딩 없이 부모 메소드를 사용하고 싶으면 super. 를 사용하면 된다.

this, this(), super, super()

  • 레퍼런스
    • this : 현재 객체의 모든 멤버 접근
    • super : 부모 클래스 멤버 접근
  • 메소드 호출
    • this() : 생성자에서 다른 생성자 호출
    • super() : 자식클래스 생성자에서 부모클래스 생성자 호출

참고

  • Animal을 Mammalia가 상속 받았으면
public class Mammalia extends Animal 
  • 메인 클래스에 객체를 선언하고 인스턴스를 만들 때
Mammalia cat = new Mammalia("happy", 10);
  • 자식 클래스로 선언하는데,
  • 부모 클래스로 객체를 선언하고, 자식 클래스의 자료형으로 만들 수 있다.
Animal cat = new Mammalia("happy", 10);
  • Mammalia is Animal 이 성립하므로 가능.
  • Animal is Mammalia는 불가능하므로 아래의 코드는 불가능
Mammalia cat = new Animal("happy", 10);
  • Object로 객체를 선언할 수도 있다.
Object cat = new Mammalia("happy", 10);
  • 자바의 모든 클래스는 Object 클래스를 상속받기 때문이다.

메소드 오버라이딩 Method overriding

  • 부모 클래스의 메소드를 자식 클래스에서 재정의해서 사용하는 것
    • 부모 클래스의 메소드 무시, 덮어쓰기

메소드 오버라이딩 조건

  • 부모 클래스 메소드와 동일 이름, 동일 매개변수 타입과 개수, 동일 리턴 타입
  • 부모 클래스 메소드 접근지정자보다 접근 범위를 좁혀서 오버라이딩은 불가능하다
    • 접근지정자 : public, protected, default, private 순으로 좁아짐
      • ex. 부모클래스에 protected로 선언되었으면, public, protected로만 오버라이딩 가능
    • static, private, final로 선언된 부모클래스 메소드는 자식 클래스에서 오버라이딩 불가능하다.


https://danmilife.tistory.com/22 참고

접근제어자 종류

  • public : 접근에 제한이 없다.
  • protected : 동일 패키지 내, 또는 파생 클래스에서 접근이 가능
  • dufault : 접근제어자 명시하지 않은 경우 기본으로 할당. 동일 패키지 내에서만 접근 가능
  • private : 자기 자신의 클래스 내에서만 접근 가능

메소드 오버로딩 Method overloading

  • 부모 클래스의 메소드와 이름은 같지만 다른 메소드를 추가하는 것.

예시 코드

메인 클래스

public class test {

    public static void main(String[] args){

        Mammalia cat = new Mammalia("happy", 10); 

        cat.aging();
        System.out.println(cat.getAge() + "살"); // 11살

        cat.aging(5);
        System.out.println(cat.getAge() + "살"); // 16살
    }
}

부모 클래스

public class Animal {
    private int age;
    private String name;

    public Animal(String name, int number) { 
        this.name = name;
        age = number;
    }

    // 멤버 함수(메소드)
    public void aging() {
        age++;
    }
}

자식 클래스

public class Mammalia extends Animal{

    public Mammalia(String name, int number) {
        super(name, number);
    }

    public void aging() {

        super.aging(); // 부모 클래스의 멤버에 접근 가능. 이거 지우면 나이는 안먹고, 털은 길어짐. == 부모 클래스의 메소드를 오버라이딩 하는 것임.
        // 이를 방지하고 싶으면, 부모클래스에서 static, private, final로 선언하면 자식클래스에서 오버라이딩이 불가능해진다.

    }

    public void aging(int time){ // 메소드 오버로드
        super.setAge(super.getAge() + time);
    }
}

다중 상속 불가능

  • extends로 여러 개의 부모 클래스를 상속 받기는 불가능하다.
  • 여러 부모에서 같은 이름의 메소드를 선언하고 있는 경우, 자식 메소드가 사용하고 있는 메소드가 어느 부모의 메소드인지 몰라 다이아몬드 문제가 발생할 수 있다.
  • 다중 상속이 필요한 경우에는 interface를 사용해서 implements를 하면 된다. implement에 대한 설명은 다음 글에 한다.

생성자 오버로딩

자식 클래스

public class Mammalia extends Animal{

    private int hair;

    public Mammalia(String name, int number) {
        super(name, number);
    }

    public Mammalia(String name, int number, String hairLength) {
        super(name, number);
        if (hairLength == "long"){
            hair = 100;
        } else {
            hair = 10;
        }
    }
}
  • 기존 생성자는 name, number만 받았지만, 오버로딩한 생성자는 hairLength까지 받는다.

메인 클래스

public class test {

    public static void main(String[] args){

        Mammalia cat = new Mammalia("happy", 10); 

        Mammalia longCat = new Mammalia("sad", 20, "long");
        System.out.println(longCat.getHair()); // 100
profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글