다음 요구사항에 따라 클래스를 구성하고 객체를 만들어보세요
경찰 근무정보
- 경찰(Police)은 권총(Gun)을 한 자루 가질 수 있습니다
- 경찰 객체는 이름과 직급, 근무지역에 대한 정보를 가지고 있습니다
- 권총 객체는 남아있는 총알 수에 대한 정보를 가지고 있습니다
- 경찰 생성 시 권총 한 자루가 자동으로 생성됩니다
- 권총이 생성되면 총알은 2발로 자동 설정됩니다
- 경찰 정보 출력 시 이름, 직급, 근무지역과 권총의 정보가 함께 출력되어야 합니다
- 권총 정보 출력 시 남아있는 총알 수가 출력되어야 합니다
- 권총은 fire 이라는 이름의 메소드를 가지고 있으며, 메소드를 실행하면 화면에 "빵야!" 라고 출력한 다음
권총의 총알 수가 한 발 줄어들게 구현해야 합니다
- fire 메소드 실행 시 권총 총알이 없다면 "딸깍!"이라고 출력하며 권총에는 아무런 변화가 일어나지 않습니다
- 경찰은 shoot 이라는 이름의 메소드를 가지고 있으며, 실행 시 가지고 있는 권총을 발사합니다
- 포돌이, 포순이, 포그리 생성 후 포돌이는 2번, 포순이는 1번, 포그리는 3번 총을 발사하도록 코드를 구현한
뒤 정보를 출력하세요
Gun 클래스
package day10_oop.modifier4;
public class Gun {
// 멤버 필드 - 총알 수
private int bullet;
// getter & setter
public int getBullet() {
return this.bullet;
}
public void setBullet(int bullet) {
if(bullet > 0) {
this.bullet = bullet;
}
}
// 생성자
Gun(int bullet){
this.setBullet(2); // 생성시 총알을 2개 가지고 있도록
}
// fire 메소드
public void fire() {
if(this.bullet > 0) {
System.out.println("빵야!");
this.bullet--;
}
else {
System.out.println("딸깍!");
}
}
// 정보 출력 메소드
public void print() {
System.out.println("남은 총알 수 :" + this.bullet);
}
}
Police 클래스
package day10_oop.modifier4;
public class Police {
// 멤버 필드
private String name, position, location;
private Gun gun; // *** Gun 객체를 멤버필드에 생성한다
// 생성자
Police(String name, String position, String location){
this.setName(name);
this.setPosition(position);
this.setLocation(location);
this.gun = new Gun(); // 경찰 객체 생성시 총 객체를 생성
}
// getter & setter
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return this.position;
}
public void setPosition(String position) {
this.position = position;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
// shoot 메소드
public void shoot() {
System.out.println(this.name + "가 총을 발사합니다!"); // 어떤 객체가 총을 발사했는지 표시하기 위함
gun.fire();
}
// 출력 메소드
public void print() {
System.out.println("이름 : " + this.name);
System.out.println("직급 : " + this.position);
System.out.println("근무지역 : " + this.location);
gun.print(); // Gun 클래스에서 gun의 남은 총알 정보를 출력하는 print 메소드를 호출
}
}
메인 메소드
package day10_oop.modifier4;
public class Test01 {
public static void main(String[] args) {
// 객체 생성
Police a = new Police("포돌이", "순경", "영등포경찰서");
Police b = new Police("포순이", "경장", "당산파출소");
Police c = new Police("포그리", "순경", "마포경찰서");
// 총알 발사
a.shoot();
a.shoot();
b.shoot();
c.shoot();
c.shoot();
c.shoot();
// 정보 출력
a.print();
b.print();
c.print();
}
}
'국비교육 > 국비교육 복습' 카테고리의 다른 글
day11_oop.keyword7 : static 변수 (클래스 변수) (0) | 2022.08.13 |
---|---|
day11_oop.keyword4 : static 메소드 - 클래스를 인스턴스 생성하지 않고도 메소드 호출 가능 (★) (0) | 2022.08.13 |
day10_oop.modifier2 : 접근제한을 붙여서 클래스 생성 (0) | 2022.08.13 |
day10_oop.getter3 : 멤버필드를 새로 정의하지 않고 총합, 평균 구하기 (2) (0) | 2022.08.13 |
day10_oop.getter2 : 멤버필드를 새로 정의하지 않고 총합, 평균 구하기 (1) (0) | 2022.08.13 |