오늘은 어제에 이어서 상속과 생성자에 대해서 알아본다.
class Man {
String name;
public Man(String name) {
this.name = name;
}
}
class BMan extend Man{
String company;
String position;
public BMan(String company, position) {
this.company = company;
this.position = position;
}
}
예를들어, 상위클래스인 Man / 하위클래스인 BMan 이
정의되어 있는 코드가 있다고 치자.
main 코드에서 BMan의 인스턴스가 생성되면 그 안에 Man 클래스의
name 변수도 클래스의 멤버가 되는데 문제는 초기화가 진행되지 않는다는 점.
그래서 상속을 할 때는
class BMan extend Man{
String company;
String position;
public BMan(String name, company, position) {
this.name = name;
this.company = company;
this.position = position;
}
}
이렇게 따로 초기화를 해줘야 한다는점.
또한 하위클래스의 인스턴스 생성 시 상위 클래스, 하위 클래스의 생성자 모두 호출되며 순서는 상위 클래스의 생성자가 먼저 호출된다.
내일은 이와 관련하여 상위 클래스의 생성자를 명시적으로 호출하는 super에 대해서 알아본다.
오늘의 코멘트: 개인 일정 끝내고 집와서 낮잠 후 새벽기상 후 포스팅..