개발동
상속 본문
상속이란, 기존 클래스의 코드를 재사용하여 새로운 클래스를 생성하는 것으로
자식클래스는 부모클래스의 멤버를 상속받는다. (초기화 블럭과 생성자는 상속 받지 아니함)
※상속이외에도 클래스간에 포함관계를 맺음으로써 클래스 재사용이 가능하다.
class Point
{
int x, y;
}
class Circle0 extends Point
{
int r;
}
class Circle
{
Point p = new Point();
int r;
}
public class ExtendsEx {
public static void main(String[] args) {
// TODO Auto-generated method stub
Circle c = new Circle();
c.p.x = 10;
c.p.y = 10;
c.r = 1;
Circle0 c0 = new Circle0();
c0.x = 10;
c0.y = 10;
c0.r = 1;
}
}
자식클래스의 생성자는 첫줄에서 부모클래스의 생성자를 호출해야한다.
부모클래스의 생성자 호출 코드가 자식클래스에 없는 경우,
컴파일러는 자식 생성자의 첫 줄에 'super();'를 자동으로 추가한다.
아래 코드는 자식클래스 생성자 Point3D(int x, int y, int z)의 첫줄에
부모클래스의 기본생성자를 호출하는 super(); 가 자동 추가되었는데
호출할 기본생성자가 정의되어있지 않아서 발생하는 오류이다.
class Point{
int x,y;
// Point(){
// this(0,0);
// }
Point (int x, int y){
this.x = x;
this.y = y;
}
String getLocation() {
return "x :" +x+", y :"+y;
}
}
class Point3D extends Point{
int z;
Point3D(int x, int y, int z){
//super();
this.x = x;
this.y = y;
this.z = z;
}
String getLocation() {
return "x :" +x+", y :"+y+", z :"+z;
}
}
public class PointTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point3D p3 = new Point3D(1,2,3);
}
}
'Programming > Java' 카테고리의 다른 글
[예제] 여러 종류의 객체를 배열로 다루기 (0) | 2021.09.26 |
---|---|
참조변수와 인스턴스의 연결 (0) | 2021.09.26 |
Calendar 클래스 (0) | 2021.09.23 |
난수 생성 (0) | 2021.09.23 |
StringTokenizer() (0) | 2021.09.23 |