■ 상속
- 상속을 하기 위해서는 extends 키워드를 사용
- 상속을 받은 자식 클래스는 부모 클래스에 선언되어 있는 private 접근 제한을 갖는 필드와 메소드를 제외한 public, protected, default로 선언되어 있는 모든 변수와 메서드를 물려받아 사용할 수 있다.
- final 키워드를 가진 클래스는 상속할 수 없다.
- 부모클래스가 먼저 생성된 후 자식 클래스가 생성된다.
■ is - a 관계
- extends로 상속 받은 경우 is-a 관계가 형성되었다고 한다.
■ super
- super는 부모 클래스의 멤버를 가리키는 참조변수
- super를 이용해 부모 클래스의 private를 제외한 멤버변수나 메소드에 접근할 수 있다.
■ super()
- 부모 객체의 생성자 부모 클래스의 생성자를 호출하는 키워드이다.
- super()는 자식 생성자 내 최상단에 위치해야 하며 다른 문장보다 뒤에 있으면 오류이다.
- 자바는 자식 클래스가 생성되기 전에 부모 클래스부터 생성을 해야 하므로 개발자가 명시적으로 super()를 사용하wl 않아도 자식 클래스의 생성자 내에 super()가 자동으로 삽입된다.
■ 상속과 구현
class Parent {
private int money = 2000;
public Parent() {
super();
// System.out.println("Parent 기본생성자");
}
public Parent(int money) {
super();
this.money = money;
// System.out.println("Parent 오버로딩 생성자");
}
public int earning() {
return this.money *= 2;
}
public void output() {
System.out.println("부모 현재 자산 : " + money + ", 투자 수익 : " + this.earning());
}
}
class Child extends Parent {
private int property = 1000;
public Child() {
System.out.println("Child 기본생성자");
// super.earning(); this.earning()과 동일
}
public Child(int property) {
super();
this.property = property;
}
public int gather() {
return property *= 3;
}
@Override
public void output() {
super.output(); // 부모의 output
System.out.println("자식 현재 자산 : " + property + ", 증식 자산 : " + this.gather());
}
@Override
public String toString() {
return "Child [property=" + property + "]";
}
}
public class InheritanceTest01 {
public static void main(String[] args) {
Child c = new Child();
c.output();
c.gather();
c.earning();
// println() 메소드는 전달인자도 객체를 받으면
// 자동으로 그 클래스의 toString()을 호출하도록 설계되어 있다
System.out.println(c.toString()); // Child가 참조하고 있는 해쉬주소
System.out.println(c); // 위 코드와 같은 결과
}
}
'프로그래밍 언어 > Java' 카테고리의 다른 글
[Java] 추상 클래스(Abstract Class) (1) | 2024.01.25 |
---|---|
[Java] 오버라이딩 (0) | 2024.01.25 |
[Java] 피트니스 프로젝트 (0) | 2024.01.23 |
[Java] final (0) | 2024.01.23 |
[Java] static (0) | 2024.01.23 |