자바의 정석 7장 (15일차) - 상속 (inheritance) & 포함 (composite)

728x90

상속 inheritance

기존의 class에서 새로운 class를 작성하는 것 (코드의 재사용)

두 class를 부모와 자식의 관계로 맺어주는 것

 

상속 inheritance를 쓰는 이유

  • 적은 양의 코드를 사용하여 새로운 class 작성 가능
  • 공통적으로 코드를 관리 가능 (새롭게 추가 or 변경) = 유지보수 용이

아래와 같이 지정할 수 있음

  • extends 함수를 사용
class parents{}
class child extends parents{}

 

자식은 조상(부모의 부모...부모) 모든 멤버 변수를 상속받는다

  • 다만 생성자와 초기화 블럭 제외

따라서 자식의 멤버변수는 항상 부모와 같거나 많다

class parents{
	int age;
    }
class child extends parents{}
// class child의 멤버변수는 0개가 아닌 1개 (*int age)이다!

 

자식 class의 변경은 조상에 영향을 미치지 않는다.

  • 아래의 코드 블럭처럼 자식의 멤버변수가 추가되어도 조상의 멤버변수에게 영향을 미치지 않음
class parents{
	int age;
    }
class child extends parents{
	public static void main(String[] args){
 		System.out.println("Hello")   
    }
}
//자식의 멤버변수는 2개지만 조상의 멤버변수는 여전히 1개!

 

아래는 extends 함수를 써서 조상과 자식을 연결한 예제

  • TV 클래스를 상속받음으로써 SmartTv 클래스를 보다 적은 함수로 작성이 가능했다.
	public static void main(String[] args) {
		SmartTv st = new SmartTv();
		st.channel = 0;
		st.channelup();
		System.out.println(st.channel);
		st.display("Hello");
		st.isCaption = true;
		st.display("Hello");
	}
}

class TV{
	int channel;
	int volume;
	
	void channelup() {
		++channel;
	}
}

class SmartTv extends TV{
	boolean isCaption;
	
	void display(String text) {
		System.out.print(isCaption ? text : "");
//		true일 경우에만 String 형식 text 출력
	}
}

포함 composite

클래스의 멤버로 참조변수를 선언하는 것

  • 대표적 예시 Random, Scanner, Array 등등
class calculator{
	Random random = new Random()
//	이런 식으로 선언하여 class를 참조변수로 쓰는 것
    }

 

작은 단위의 클래스를 만들고 이 클래스들을 조합해서 큰 클래스를 만든다.

  • 위의 예시를 가져와서 동일하지만 상속에서 포함이 된 클래스로 만들었다.
  • 차이점은 main 함수에서 print를 할 때 st.t.channel로 선언법이 바뀜
	public static void main(String[] args) {
		SmartTv st = new SmartTv();
		st.t.channel = 0;
		st.t.channelup();
		System.out.println(st.t.channel);
		st.display("Hello");
		st.isCaption = true;
		st.display("Hello");
	}
}

class SmartTv{
	TV t = new TV();
	boolean isCaption;
	
	void display(String text) {
		System.out.print(isCaption ? text : "");
//		true일 경우에만 String 형식 text 출력
	}
}

상속과 포함 관계 결정 방법

대부분의 클래스가 포함, Composite으로 결정되고 나머지가 상속, Inheritance지만 판단하기 어려울 때는 아래와 같이 결정 가능

  • 상속: Inheritance, ~은/는 ~이다 (is~a)
  • 포함: Composite, ~은/는 ~을/를 가지고 있다. (has~a)

 

아래의 예시를 이용해보면, 'SmartTv는 Tv를 가지고 있다' 보다는 'SmartTv는 Tv이다' 라는 표현이 더 적절하므로 상속(inheritance)를 사용하는 것이 적절

class SmartTv{
	TV t = new TV();
	boolean isCaption;
	
	void display(String text) {
		System.out.print(isCaption ? text : "");
//		true일 경우에만 String 형식 text 출력
	}
}
728x90