추상 클래스
- 추상 메소드를 1개 이상 가지고 있는 클래스
- (public 앞뒤 상관없지만 일반적으로 뒤에)
abstract 키워드를 추가한다
- 추상 클래스는 객체를 생성할 수 없음 (미완성된 클래스이기 때문)
- 추상 클래스의 서브 클래스는 "반드시" 추상 메소드를 오버라이드해야 함
package ex08_abstract;
public abstract class Person {
public void eat() {
System.out.println("냠냠");
}
public void sleep() {
System.out.println("쿨쿨");
}
public abstract void study();
}
인터페이스
- JDK 1.7 이전에는 "추상 메소드 + final 상수"로만 구성된 추상 클래스를 의미
- JDK 1.8 이후로는 "추상 메소드 + default 메소드 + static 메소드 + final 상수"로 구성
1) 추상 메소드 : 본문이 없는 메소드 (인터페이스 대부분은 추상 메소드로 구성됨)
2) default 메소드 : 본문이 있는 메소드
3) static 메소드 : 클래스 메소드 (본문 있음)
- 인터페이스의 추상 메소드는
public abstract를 생략할 수 있음
public class SmartPhone extends Camera implements Phone, Computer
- 인터페이스는 다중 구현이 가능 (SmartPhone에서 phone,computer 두 인터페이스 구현함)
- 클래스 상속과 인터페이스 구현을 동시에 할 수 있음 (적을 때 순서 상속 먼저, 구현 나중에)
클래스 상속 vs 인터페이스 구현
- 클래스를 상속받는다.
public class Person { }
public class Student extends Person { }
- 인터페이스를 구현한다
public interface Shape { }
public class Rectangle implements Shape { }
- 인터페이스를 구현한 클래스는 "반드시" 추상 메소드를 오버라이드해야 한다
추상 클래스의 서브 클래스는 "반드시" 추상 메소드를 오버라이드해야 하니까
- java는
다중상속을 지원하지 않는다.
문제
ex02_Computer
class Computer
package ex02_Computer;
public class Computer {
private String model;
public Computer(String model) {
this.model = model;
}
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;
public int getBattery() {
return battery;
}
public void setBattery(int battery) {
this.battery = battery;
}
public Notebook(String model, int battery) {
super(model);
this.battery = battery;
}
}