본문 바로가기

자바

클래스의 포함 관계 예제 (클래스를 필드멤버 처럼 사용)

PohamMain


package pack.your;


public class PohamMain {

public static void main(String[] args) {

PohamCar kildong = new PohamCar("길동");

kildong.turnHandle(30);

System.out.println(kildong.ownerName + "의 회전량은 " + kildong.turnShow + kildong.handle.quantity); //  kildong.handle.quantity 포함관계로 접근한 경우

PohamCar sunsin = new PohamCar("순신");

sunsin.turnHandle(-20);

System.out.println(sunsin.ownerName + "의 회전량은 " + sunsin.turnShow + sunsin.handle.quantity); //  kildong.handle.quantity 포함관계로 접근한 경우

}

}


=====================================================================================================================

PohamHandle 


package pack.your;


public class PohamHandle {

int quantity;

public PohamHandle(){

quantity = 0;

}

String leftTurn(int q){

quantity = q;

return "좌회전";

}

String rightTurn(int q){

quantity = q;

return "우회전";

}

String straight(int q){

quantity = q;

return "직진";

}


}


=====================================================================================================================

PohamCar 


package pack.your;


public class PohamCar {

String ownerName, turnShow;

PohamHandle handle; // 클래스의 포함 - 필드처럼 사용

public PohamCar() {

}

public PohamCar(String name) {

ownerName = name;

handle = new PohamHandle();

}

void turnHandle(int q){

if(q > 0) turnShow = handle.rightTurn(q);

if(q < 0) turnShow = handle.leftTurn(q);

if(q == 0) turnShow = handle.straight(q);

}

}