[Java]상속3
- IS-A 관계
상속을 위한 관계에는 2가지 관계가 존재합니다. 첫번 째는 일종의 관계인 IS-A관계로 핸드폰의 경우 기존의 전화기에서 들고 다닐 수 있는 기능이 노트북 또한 컴퓨터에서 휴대성이 추가되었습니다. 따라서 아래와 같은 문장으로 관계를 표현을 할 수 있습니다.
- 핸드폰은 is a 전화기 입니다.(핸드폰은 일종의 전화기 입니다.)
- 노트북은 is a 컴퓨터 입니다.(노트북은 일종의 컴퓨터 입니다.)
상위 클래스를 상속받은 하위 클래스도 상위 클래스가 지니고 있는 모든 것을 가지고 있고, 거기에 추가적인 특성이 더해진 것 입니다. 아래의 예제를 보면 Computer을 상속받은 NotebookComp는 calulate()의 기능을 가지면서도 추가적인 기능으로 배터리를 충전하는 기능인 charging(), 움직이면서 전화를 하는 movingCall()의 기능을 가지고 있습니다.
class Computer{
String owner;
public Computer(String name) { owner = name;}
public void calculate() {System.out.println("Calculate the requested content");}
}
class NotebookComp extends Computer{
int battery;
public NotebookComp(String name, int initChag) {
super(name);
battery = initChag;
}
//additional characteristics.
public void charging() { battery += 5;}
public void movingCall() {
if(battery < 1) {
System.out.println("battery is low");
return;
}
System.out.println("moving call");
calculate(); //parent class member.
battery--;
}
}
class TableNotebook extends NotebookComp{
String registeredpen;
public TableNotebook(String name, int initChag, String pen) {
super(name, initChag);
registeredpen = pen;
}
//aditional characteristics.
public void write(String penInfo) {
if(battery < 1) {
System.out.println("battery is low");
return;
}
if(registeredpen.compareTo(penInfo) !=0) {
System.out.println("Not a registered pen");
return;
}
System.out.println("Process your handwriting");
}
}
public class ISAInheritance {
public static void main(String[] args) {
// TODO Auto-generated method stub
NotebookComp nc = new NotebookComp("Lee", 10);
TableNotebook tc = new TableNotebook("Kim", 20, "13304");
nc.movingCall();
tc.movingCall();
tc.write("13304");
}
}
- HAS-관계
그 다음의 관계로는 소유의 관계로 HAS-A관계가 있습니다.
class Gun{
int bullet;
public Gun(int bnum) { bullet = bnum; }
public void shot() {
if(bullet < 1) {
System.out.println("No bullet");
return;
}
System.out.println("Bang!!");
bullet--;
}
}
//police with gun
class Police extends Gun{
int handcuffs;
public Police(int bnum, int hnum) {
super(bnum);
handcuffs = hnum;
}
public void putHandcuffs() {
if(handcuffs < 1) {
System.out.println("No handcuffs");
return;
}
System.out.println("Snap!!");
handcuffs--;
}
}
public class HASInheritance {
public static void main(String[] args) {
// TODO Auto-generated method stub
Police policeA = new Police(10, 4);
Police policeB = new Police(0, -1);
System.out.println("A");
policeA.shot();
policeA.putHandcuffs();
System.out.println("B");
policeB.shot();
policeB.putHandcuffs();
}
}
위 예제를 보면 경찰 클래스가 총 클래스를 상속받아 총을 든 경찰을 만들었습니다. 하지만 이 관계는 권장 되지 않는 관관계입니다. 그 이유는 확장성에 대해 매우 안좋은 코드이기 때문입니다. 예를 들어 총을 든 경찰에 전기봉을 추가하여야 한다면, 다중 상속을 허용하지 않는 JAVA에서는 상위 클래스인 Gun을 다시 수정해 전기봉을 추가하여야 합니다. 이렇게 되면 전체 코드에 많은 부분을 수정해야 해 많은 시간과 비용이 들어가게 됩니다. 이처럼 상속으로 묶인 두 개의 클래스는 강한 연관성을 띠므로 확장에 대해 용이하지 않습니다.
- 복합 관계
확장성에 용이하게 짜기위해서는 상속의 관계보다는 하나의 클래스를 인스턴스로 생성하여 코드를 짜는 것이 좋습니다. 그럼 전기봉을 추가할 때 Gun클래스는 건들지 않고 전기봉 클래스를 새로 만들어 Police에 전기봉 클래스 인스턴스를 생성해주면 되기 때문입니다.
class Gun{
int bullet;
public Gun(int bnum) {bullet =bnum;}
public void shot() {
System.out.println("BBang");
bullet--;
}
}
class Police{
int handcuffs;
Gun gun;
public Police(int cuffnum, int bnum) {
handcuffs = cuffnum;
//gun.bullet = bnum; // 오류의 원인 : 참조변수만이 존재하기 때문에 인스턴스를 생성시켜줘야한다.
if(bnum > 0) {
gun = new Gun(bnum);
}
else gun = null;
}
public void putHandcuff() {
if(handcuffs < 1) {
System.out.println("not exist");
return;
}
else {
System.out.println("Snap");
handcuffs--;
}
}
public void shot() {
if(gun == null) {
System.out.println("Hut BBang");
return;
}
else gun.shot();
}
}
public class HASAComposite {
public static void main(String[] args) {
// TODO Auto-generated method stub
Police policeA = new Police(3,5);
Police policeB = new Police(0,0);
policeA.shot();
policeA.putHandcuff();
policeB.shot();
policeB.putHandcuff();
}
}
상속의 관계를 사용하는 것은 IS-A관계일 때 사용하는 것이 제일 많은 장점을 가지는 것 같습니다!