상세 컨텐츠

본문 제목

자바 JAVA IS-A HAS-A 예시

카테고리 없음

by 가난한마음 2024. 4. 12. 11:52

본문

*
 * [IS-A 관계]
 * :IS-A 관계는 상속 관계를 나타내며, 객체 지향 프로그래밍에서 한 클래스가 다른 클래스의 하위 클래스인 경우를 말합니다.
 * : ~는 ~다.
 * ex1) 학생은 사람이다. ( O )
 * ex2) 사람은 학생이다. ( X )
 * 
 * [HAS- A 관계] 또는 소유관계, 포함관계
 * : HAS-A 관계는 한 클래스가 다른 클래스의 객체를 포함하는 관계를 나타냅니다.
 * : ~가(는) ~를 소유(포함)하고 있다.
 * ex1) 스마트폰은 카메라를 포함하고 있다.(O)
 * ex2) 카메라가 스마트폰을 포함하고 있다. (X)

*/
class Gun {
	int bullet;
	
	public Gun(int bnum) {
			bullet = bnum;
	}
	public void shoot(){
			System.out.println("BBANG");
			bullet--;
	}
}

class Police {
	int handcuffs; // primitive type
	Gun pistol; // reference type (G)시작이 대문자)
	
	public Police(int bnum, int bcuff) {
		handcuffs = bcuff;
		if(bnum!= 0)
					pistol = new Gun(bnum);
		else
					pistol = null;
	}
	public void putHandcuff() {
			System.out.println("SNAP!");
			handcuffs--;
	}
	public void shoot() {
		if(pistol == null)
						System.out.println("Hut BBANG!");
		else
						pistol.shoot();
	}
}

public class Inheritance05refactoring {

	public static void main(String[] args) {
		Police pman = new Police(5,3);
		pman.shoot();
		pman.putHandcuff();

	}

}​
/*
 * [IS-A 관계]
 * :IS-A 관계는 상속 관계를 나타내며, 객체 지향 프로그래밍에서 한 클래스가 다른 클래스의 하위 클래스인 경우를 말합니다.
 * : ~는 ~다.
 * ex1) 학생은 사람이다. ( O )
 * ex2) 사람은 학생이다. ( X )
 * 
 * [HAS- A 관계] 또는 소유관계, 포함관계
 * : HAS-A 관계는 한 클래스가 다른 클래스의 객체를 포함하는 관계를 나타냅니다.
 * : ~가(는) ~를 소유(포함)하고 있다.
 * ex1) 스마트폰은 카메라를 포함하고 있다.(O)
 * ex2) 카메라가 스마트폰을 포함하고 있다. (X)

*/
class Gun {
	int bullet;
	
	public Gun(int bnum) {
			bullet = bnum;
	}
	public void shoot(){
			System.out.println("BBANG");
			bullet--;
	}
}

class Police extends Gun {
	  int handcuffs; // 소유한 수갑의 수
	  
	  public Police(int bnum, int bcuff) {
	  		super(bnum);
	  		handcuffs = bcuff;
		}	
	  public void putHandcuff(){
		  	 System.out.println("SNAP");
		  	 handcuffs--;
	  }
}

public class InheritanceEx05 {

	public static void main(String[] args) {
		Police pman = new Police(5,3);
		pman.shoot();
		pman.putHandcuff();

	}

}