문제
아래의 5개의 클래스를 작성하고, 메인에서 아래와 같은 실행 결과를 출력하시오(추상 클래스)
Ship, Boat, Cruise, ShipUtill, ShipExample
Ship Class(조상 / 추상클래스)
멤버변수
int person
int weapon
멤버함수
생성자구현
public abstract int move(void) *인원
public abstract int carry(void) *무기
Boat Class(자손클래스)
멤버변수
String name
멤버함수
public int move(void) *인원
public int carry(void) *무기
public String name(void)
Cruise Class(자손 클래스)
멤버변수
String name
멤버함수
public int move(void) *인원
public int carry(void) *무기
public String name(void)
ShipUtill Class(독립클래스)
멤버함수
static void search(Ship s) *instanceof연산자 이용
ShipExample(실행클래스)
결과
Boat가 나를 수 있는 인원 입력 : 6
Boat가 나를 수 있는 무기 입력 : 0
Boat 이름 입력 : 쌩쌩
Cruise가 나를 수 있는 인원 입력 : 300
Cruise가 나를 수 있는 무기 입력 : 200
Cruise 이름 입력 : 전함 무궁화
Boat 이름: 쌩쌩, 인원 : 6, 무기 : 0
Cruise 이름: 전함, 인원 : 300, 무기 : 200
코드
abstract class Ship {
int person;
int weapon;
public Ship(int person, int weapon) {
super();
this.person = person;
this.weapon = weapon;
}
public abstract int move();
public abstract int carry();
}
class Boat extends Ship {
String name;
public Boat(int person, int weapon, String name) {
super(person, weapon);
this.name = name;
}
public int move() {
return person;
}
public int carry() {
return weapon;
}
public String name() {
return name;
}
}
class Cruise extends Ship {
String name;
public Cruise(int person, int weapon, String name) {
super(person, weapon);
this.name = name;
}
public int move() {
return person;
}
public int carry() {
return weapon;
}
public String name() {
return name;
}
}
class ShipUtill {
static void search(Ship s) {
if (s instanceof Boat) {
System.out
.println("Boat 이름: " + ((Boat) s).name() + ", " + "인원 : " + s.move() + ", " + "무기 : " + s.carry());
}
else if (s instanceof Cruise) {
System.out.println(
"Cruise 이름: " + ((Cruise) s).name() + ", " + "인원 : " + s.move() + ", " + "무기 : " + s.carry());
}
}
}
class ShipExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Boat가 나를 수 있는 인원 입력 : ");
int boatNum = sc.nextInt();
System.out.print("Boat가 나를 수 있는 무기 입력 : ");
int boatWeapon = sc.nextInt();
System.out.print("Boat 이름 입력 : ");
String boatName = sc.next();
Boat boat = new Boat(boatNum, boatWeapon, boatName);
System.out.print("Cruise가 나를 수 있는 인원 입력 : ");
int CruiseNum = sc.nextInt();
System.out.print("Cruise가 나를 수 있는 무기 입력 : ");
int CruiseWeapon = sc.nextInt();
System.out.print("Cruise 이름 입력 : ");
String CruiseName = sc.next();
Cruise cruise = new Cruise(CruiseNum, CruiseWeapon, CruiseName);
//ShipUtill ship = new ShipUtill();
ShipUtill.search(boat);
ShipUtill.search(cruise);
}
}
ShipUtill 클래스의 search 메소드가 static이기 때문에 물론 객체를 생성해서 이 메소드를 호출해도 되지만
클래스 명으로 바로 접근이 가능하다는 것을 잘 살피자
'Java' 카테고리의 다른 글
| [Java] (interface) (17-2) (0) | 2023.08.30 |
|---|---|
| [Java] interface (17-1) (0) | 2023.08.30 |
| [Java] (추상 클래스) (16-1) (0) | 2023.08.30 |
| [Java] 클래스 (상속, 오버라이딩, 다형성, 스택, 팝) (15) (0) | 2023.08.27 |
| [Java] 클래스 (상속, 오버라이딩, 다형성) (15) (0) | 2023.08.27 |