Java는 단일 상속만을 허용한다.
비중이 높은 클래스 하나만 상속관계로, 나머지는 포함관계로 한다.
class Tv {
boolean power;
int channel;
void power() { power = !power; }
void channelUp() { ++channel; }
void channelDown() { --channel; }
}
class VCR {
boolean power;
int counter = 0;
void power() { power = !power; }
void play() { }
void stop() { }
void rew() { }
void ff() { ]
}
--------------------------------------
class TVCR extends Tv {
VCR vcr = new VCR();
int counter = vcr.counter;
void play() {
vcr.play();
}
void play() {
vcr.play();
}
void stop() {
vcr.stop();
}
void ff() {
vcr.ff();
}
}
조상클래스로부터 상속받은 메서드의 내용을 상속받는 클래스에 맞게 변경하는 것을 오버라이팅이라고 한다.
-> 오버로딩(overloading) - 기존에 없는 새로운 메서드를 정의하는 것(new)
-> 오버라이딩(overriding) - 상속받은 메서드의 내용을 변경하는 것(modify)
class Point {
int x;
int y;
String getLocation() {
return "x :" + x + ", y :" + y;
{
}
class Point3D extends Point {
int z;
String getLocation() {
return "x :" + x + ",y :" + y + ",z :" + z;
}
}
class Point {
int x;
int y;
String getLocation() {
return "x : " + x + ", y : " + y;
}
}
class Point3D extends Point {
int z;
String getLocation() {
//return "x : " + x + ", y : " + y + ", z : " + z;
return super.getLocation() + ", z : " + z;
}
}
super.getLocation()을 통해 조상클래스 메서드를 호출하는 것이 좋다.
(코드의 재사용성을 높이고, 조상코드가 바껴도 자동으로 변경되기 때문에)
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
//생략
}
class Point3D extends Point {
int z;
Point3D(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
//생략
}
class PointTest {
public static void main(String args[]) {
Point3D p3 = new Point3D(1,2,3);
}
}
// 에러 발생 !!
// 해결 방법 1
Point() {} //기본생성자 생성
// 해결 방법 2
Point3D(int x, int y, int z) {
super(x,y);
this.z = z;
} //super 이용