Contents
상속과 생성자기존의 클래스로부터 필드와 메서드를 이어받아 필요한 기능을 추가할 수 있는 기능
자식클래스명 + extends + 부모클래스명 { }
class Shape {
int x, y;
}
class Circ extends Shape {
int radius;
public Circ(int radius) {
this.radius = radius;
super.x = 0;
super.y = 0;
}
double getArea() {
return 3.14 * radius * radius;
}
}
public class CircleText01 {
public static void main(String[] args) {
Circ c = new Circ(10);
System.out.println("원의 넓이:" + c.getArea());
System.out.println("원의 좌표:" + c.x + "," + c.y);
}
}
이 코드에서 Citc 클래스는 Shape를 상속받는다.
이때 부모 클래스의 변수 x와 y를 이용할 수 있는데 표기할 때 super 를 사용해서 부모 클래스의 변수를 구분한다.

상속과 생성자
class Base {
public Base() {
System.out.println("부모 생성자");
}
}
class Dervied extends Base {
public Dervied() {
System.out.println("자식 생성자");
}
}
public class Rectangle {
public static void main(String[] args) {
Dervied d = new Dervied();
}
}
메인 메서드에서 자식 클래스의 메서드 Dervied 를 호출했다.

자바는 자식 클래스의 생성자를 호출하면 부모 클래스의 생성자가 먼저 호출된다.
class Base {
public Base() {
System.out.println("디폴트 생성자");
}
public Base(int x) {
System.out.println("매개변수 있는 생성자");
}
}
class Dervied extends Base {
public Dervied() {
System.out.println("자식 클래스");
}
}
public class Rectangle {
public static void main(String[] args) {
Dervied d = new Dervied();
}
}
이번에는 부모 클래스에 매개변수가 있는 생성자와 매개변수가 없는 디폴트 생성자가 있다.

이 코드를 실행하면 디폴트 생산자를 호출한다.
이때 자식 클래스의 생성자에 super(매개변수) ; 를 사용하면 된다.
class Base {
public Base() {
System.out.println("디폴트 생성자");
}
public Base(int x) {
System.out.println("매개변수 있는 생성자");
}
}
class Dervied extends Base {
public Dervied() {
super(10); //
System.out.println("자식 클래스");
}
}
public class Rectangle {
public static void main(String[] args) {
Dervied d = new Dervied();
}
}

super(매개변수) ; 는 매개변수 있는 생성자, super() ; 는 디폴트 생성자를 호출한다.
super() ; 생략되어 있어 자동 디폴트 생성자 호출이 된다.
Share article