기존의 클래스로 새로운 클래스를 작성하여 코드를 재사용하는 것
두 클래스간에 부모-자식 관계를 맺어주는 것
extends
키워드 사용
자손은 조상의 모든 멤버를 상속받음 (단, 생성자와 초기화 블럭은 제외)
자손의 멤버 개수는 적어도 조상과 같거나 많음 (적을 수 없음)
자손의 변경은 조상에 영향을 미치지 않음
class Tv {
boolean power;
int channel;
void power() { power = !power; }
void channelUp() { ++channel; }
void channelDown() { --channel; }
}
class SmartTv extends Tv { // Tv를 상속받음
boolean caption;
void displayCaption(String text) {
if (caption) {
System.out.println(text);
}
}
}
public class ch7_1 {
public static void main(String[] args) {
SmartTv stv = new SmartTv();
stv.power();
stv.channel = 9;
stv.channelUp();
stv.caption = !stv.caption;
stv.displayCaption("hello world");
System.out.println(stv.power + ", " + stv.channel);
}
}
클래스의 멤버로 참조변수를 선언하는 것
class Tv {
boolean power;
int channel;
void power() { power = !power; }
void channelUp() { ++channel; }
void channelDown() { --channel; }
}
class SmartTv { // Tv를 포함하고 있음
Tv tv = new Tv();
boolean caption;
void displayCaption(String text) {
if (caption) {
System.out.println(text);
}
}
}
public class ch7_1 {
public static void main(String[] args) {
SmartTv stv = new SmartTv();
stv.tv.power();
stv.tv.channel = 9;
stv.tv.channelUp();
stv.caption = !stv.caption;
stv.displayCaption("hello world");
System.out.println(stv.tv.power + ", " + stv.tv.channel);
}
}
[자바의 정석 - 기초편] ch7-3,4 클래스 간의 관계, 상속과 포함