2016-07-28 1 views
1

두 하위 클래스에서 값을 가져 오는 데 문제가 있습니다. 두 개의 다른 클래스에서 주 프로그램으로 값을 반환하려면 어떻게해야합니까? 클래스에는 계층 구조가 있고 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; 
} 
} 
+1

'동물'유형의 객체 만 만듭니다. 고양이를 원하면이 유형의 개체를 만들어야합니다. 'Animal myCat = new Cat ("Kitty", 2, 9)' – Blobonat

+4

처럼 할 수 있습니다. 또한, 당신이 그것을 인스턴스화 할 수 없도록 Animal abstract를 만드는 것이 합리적입니다. 그런 다음 이러한 메서드에 액세스 할 수있는 Cat 객체를 만들어야합니다. 내가 말할 수있는 것부터, 이것이 당신이하려는 일인 것처럼 보입니다. – James

+0

상위 클래스 참조를 사용하여 하위 클래스 개체를 보유 할 수 있습니다. 그러나 자식 클래스의 특정 메서드에 액세스하려면 각각 자식 클래스 – JavaHopper

답변

0

,은 모든 CatAnimal이지만 모든 AnimalCat이 아니라는 것을 의미합니다.

코드에서 new Animal(name, 0)을 사용하여 동물을 만들었으므로 Animal- 개체가 있지만 Cat이 아닙니다. 해마 일 수도 있습니다.

Animal newAnimal = new Cat(name, 0,9)을 사용하더라도 Cat- 방법에 액세스 할 수 없습니다. 당신이 만든 AnimalCat입니다.하지만 모든 컴파일러는 newAnimal에 대해 알고 있습니다. Animal newAnimal을 사용할 때 말한 내용입니다 - Animal입니다.

Cat newAnimal = new Cat(name, 0,9); 

을하지만 당신은 당신이 탐구 할 상속의 대부분의 기능을 상실 할 것이다 :

그래서 당신도 당신이 처음부터 Cat를 사용하고 말할 수 있습니다. 대안으로 유형 검사를 사용하고 나중에 캐스팅 할 수 있습니다.

if(newAnimal instanceof Cat) { 
    Cat aCat = (Cat)newAnimal; 
    /*...*/ 
    aCat.lifesBefore() 
    /*...*/ 
} 
+0

코드를 수정했지만 여전히 작동하지 않습니다. –