상속의 치명적인 오해
정답
상속의 가장 기본적인 특성
class Man {
String name;
public void tellYourName() {
System.out.println("My name is " + name);
}
}
// Man 클래스를 상속 ( extends 키워드 사용 )
class BusinessMan extends Man {
String company;
String position;
public void tellYourInfo() {
System.out.println("My company is " + company);
System.out.println("My position is " + position);
tellYourName();
}
}
상속 관련 용어의 정리와 상속의 UML 표현
상속과 생성자 ( 1 )
class Man {
String name;
public Man(String name) {
this.name = name;
}
public void tellYourName() {
System.out.println("My name is " + name);
}
}
// 문제점 : BusinessMan 생성시 그 안에 존재하는 상속받은 Man의 name은 초기화가 되지 않음
class BusinessMan extends Man {
String company;
String position;
public BusinessMan(String company, String position) {
this.company = company;
this.position = position;
}
public void tellYourInfo() {
System.out.println("My company is " + company);
System.out.println("My position is " + position);
tellYourName();
}
}
BusinessMan
클래스에서 초기화 => 생성자를 통한 초기화 원칙에 어긋남!class BusinessMan extends Man {
String company;
String position;
public BusinessMan(String name, String company, String position) {
// 상위 클래스 Man의 멤버 초기화
this.name = name;
// 클래스 BusinessMan의 멤버 초기화
this.company = company;
this.position = position;
}
public void tellYourInfo() { . . . }
}
// 상위 클래스
class SuperCLS {
public SuperCLS() {
System.out.println("I'm Super Class");
}
}
// 자식 클래스
class SubCLS extends SuperCLS {
public SubCLS() {
System.out.println("I'm Sub Class");
}
}
class SuperSubCon {
public static void main(String[] args) {
// 상위 클래스의 생성자가 먼저 실행 => 하위 클래스 생성자 실행
new SubCLS();
// I'm Super Class
// I'm Sub Class
}
}
super()
: 상위 클래스의 생성자 호출을 명시할 수 있습니다.class SuperCLS {
public SuperCLS() {
System.out.println("...");
}
public SuperCLS(int i) {
System.out.println("...");
}
public SuperCLS(int i, int j) {
System.out.println("...");
}
}
class SubCLS extends SuperCLS {
public SubCLS() {
System.out.println("...");
}
public SubCLS(int i) {
super(i);
System.out.println("...");
}
// 오버로딩
public SubCLS(int i, int j) {
super(i, j);
System.out.println("...");
}
}
class Man {
String name;
public Man(String name) {
this.name = name;
}
public void tellYourName() {
System.out.println("My name is " + name);
}
}
class BusinessMan extends Man {
String company;
String position;
public BusinessMan(String name, String company, String position) {
super(name);
this.company = company;
this.position = position;
}
public void tellYourInfo() {
System.out.println("My company is " + company);
System.out.println("My position is " + position);
tellYourName();
}
}
static
은 부모 것이 아님으로 상속이 불가class SuperCLS {
static int count = 0; // 클래스 변수
public SuperCLS() {
count++; // 클래스 내에서는 직접 접근이 가능
}
}
class SubCLS extends SuperCLS {
public void showCount() {
// private가 아니면 자식도 부모가 가지는 접근 권한만 가지게 됩니다!
System.out.println(count); // 상위 클래스에 위치하는 클래스 변수에 접근
}
}