두 하위 클래스에서 값을 가져 오는 데 문제가 있습니다. 두 개의 다른 클래스에서 주 프로그램으로 값을 반환하려면 어떻게해야합니까? 클래스에는 계층 구조가 있고 Cat.java는 Animal.Java를 상속합니다. Animal 클래스에서 값을 가져올 수 있지만 확장 Cat 클래스에서 값을 가져올 수 없습니다. 내가 도대체 뭘 잘못하고있는 겁니까?클래스를 통해 값 확장 및 반환
메인 프로그램
import java.util.*;
public class animalProject {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to create your very own animal.");
System.out.println("Start by typing a name for your animal: ");
String name = input.next();
Animal newAnimal = new Animal(name, 0);
System.out.println("New Animal created");
System.out.println("Set state of your animal: [1] Alive. [2] Dead. ");
int status = input.nextInt();
newAnimal.animalState(status);
System.out.println("Print name of your animal? [1] Yes [2] No ");
int answer = input.nextInt();
if (answer == 1) {
newAnimal.getName();
}
System.out.println("Check status of your animal? [1] Yes [2] No");
answer = input.nextInt();
if (answer == 1) {
newAnimal.checkState();
}
System.out.println("Set lifes for your cat: ");
int life = input.nextInt();
// set lifes to lifesBefore(). in Cat.Java
System.out.println("Remove lifes from cat?: [1] Yes [2] No");
while (true) {
life = input.nextInt(); {
// call the method to decrease lifes from Cat.Java
}
if (life == 2){
break;
}
}
System.out.println("Check cats lifes? [1] Yes [2] No");
answer = input.nextInt();
if (answer == 1) {
// return lifes from Cat.java
}
Animal.Java
public class Animal{
protected String name;
protected int status;
public Animal(String animalName, int animalStatus){
name = amimalName;
state = animalStatus;
}
public void getName() {
System.out.println(name);
}
public void setName() {
this.name = name;
}
public void animalState(int status) {
if (status == 1) {
state = 1; // dead
}
else if (status == 2) {
state = 2; // alive
}
else {
System.out.println("Error with setting state.. program closing..");
System.exit(1);
}
}
public void checkState() {
if (state == 1) {
System.out.println("Animal is dead ");
}
else if (state == 2) {
System.out.println("Animal is alive");
}
else {
System.out.println("Unkown input.. program closing..");
System.exit(1);
}
}
}
Cat.Java
public class Cat extends Animal {
private int catLifes;
public Cat(String animalName int animalStatus, int lifes) {
super(animalName, animalStatus);
catLifes = lifes;
}
public void lifesBefore(){
this.catLifes = lifes;
}
public void decreaseLifes() {
for (int i = 0 ; i < catLifes; i++) {
catLifes--;
}
System.out.println("Cat ran out of lifes and is now dead! ");
// set animals state to dead in Animal.Java
}
public int catsLifesAfter(){
return this.catLifes;
}
}
'동물'유형의 객체 만 만듭니다. 고양이를 원하면이 유형의 개체를 만들어야합니다. 'Animal myCat = new Cat ("Kitty", 2, 9)' – Blobonat
처럼 할 수 있습니다. 또한, 당신이 그것을 인스턴스화 할 수 없도록 Animal abstract를 만드는 것이 합리적입니다. 그런 다음 이러한 메서드에 액세스 할 수있는 Cat 객체를 만들어야합니다. 내가 말할 수있는 것부터, 이것이 당신이하려는 일인 것처럼 보입니다. – James
상위 클래스 참조를 사용하여 하위 클래스 개체를 보유 할 수 있습니다. 그러나 자식 클래스의 특정 메서드에 액세스하려면 각각 자식 클래스 – JavaHopper