[230726] 추상클래스, 인터페이스, 상속 문제 (DAY21)

MJ·2023년 7월 26일

수업 TIL🐣💚

목록 보기
22/68

추상 클래스

  1. 추상 메소드를 1개 이상 가지고 있는 클래스
  2. (public 앞뒤 상관없지만 일반적으로 뒤에) abstract 키워드를 추가한다
  3. 추상 클래스는 객체를 생성할 수 없음 (미완성된 클래스이기 때문)
  4. 추상 클래스의 서브 클래스는 "반드시" 추상 메소드를 오버라이드해야 함
package ex08_abstract;

public abstract class Person {

  public void eat() {
    System.out.println("냠냠");
  }

  public void sleep() {
    System.out.println("쿨쿨");
  }

  // 호출을 위해서 생성한 study
  // 본문이 없는 메소드를 "추상 메소드"라고 함
  // abstract 키워드를 추가하고 본문{ } 제거
  public abstract void study();
}

인터페이스

  1. JDK 1.7 이전에는 "추상 메소드 + final 상수"로만 구성된 추상 클래스를 의미
  2. JDK 1.8 이후로는 "추상 메소드 + default 메소드 + static 메소드 + final 상수"로 구성
    1) 추상 메소드 : 본문이 없는 메소드 (인터페이스 대부분은 추상 메소드로 구성됨)
    2) default 메소드 : 본문이 있는 메소드
    3) static 메소드 : 클래스 메소드 (본문 있음)
  3. 인터페이스의 추상 메소드는 public abstract를 생략할 수 있음
public class SmartPhone extends Camera implements Phone, Computer
  • 인터페이스는 다중 구현이 가능 (SmartPhone에서 phone,computer 두 인터페이스 구현함)
  • 클래스 상속과 인터페이스 구현을 동시에 할 수 있음 (적을 때 순서 상속 먼저, 구현 나중에)

클래스 상속 vs 인터페이스 구현

  1. 클래스를 상속받는다.
    public class Person { }
    public class Student extends Person { }
  2. 인터페이스를 구현한다
    public interface Shape { }
    public class Rectangle implements Shape { }
  • 인터페이스를 구현한 클래스는 "반드시" 추상 메소드를 오버라이드해야 한다
    추상 클래스의 서브 클래스는 "반드시" 추상 메소드를 오버라이드해야 하니까
  • java는 다중상속을 지원하지 않는다.

문제

ex02_Computer

class Computer

package ex02_Computer;

public class Computer {
  private String model;

  // Notebook 생성자의 super(model);에 의해서 호출되는 생성자
  public Computer(String model) {
    this.model = model;
  }

  //Getter Setter
  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }
}

class Notebook

package ex02_Computer;

public class Notebook extends Computer {

  private int battery;

  //Getter Setter
  public int getBattery() {
    return battery;
  }

  public void setBattery(int battery) {
    this.battery = battery;
  }

  // new Notebook("gram",70)에 의해서 호출되는 생성자
  public Notebook(String model, int battery) {
    super(model); //super는 항상 먼저 호출해야 함. 순서만 바꿔도 오류
    this.battery = battery;
  }
}
  • super()는 항상 먼저 호출해야 함

0개의 댓글