我在介紹性的java課程,我們剛開始學習繼承。我正在研究一項任務,要求我們創建一個名稱和年齡爲「Pet」的超類;和三個亞類,每個亞類都有自己獨特的特徵(我選擇了「狗」,「貓」和「鳥」)。在完成所有這些構建之後,我們將創建一個Main類來測試所有內容,這就是我遇到問題的地方。我試圖在Main
內調用get
這些獨特特徵的方法,但它似乎只能找到超類中的方法。從超類調用子類方法
這裏是主類:
public class Kennel {
public static void main(String[] args) {
// Create the pet objects
Pet cat = new Cat("Feline", 12, "Orange");
Pet dog = new Dog("Spot", 14, "Dalmation");
Pet bird = new Bird("Feathers", 56, 12);
// Print out the status of the animals
System.out.println("I have a cat named " + cat.getName()
+ ". He is " + cat.getAge() + " years old."
+ " He is " + cat.getColor()
+ "When he speaks he says " + cat.speak());
System.out.println("I also have a dog named " + dog.getName()
+ ". He is " + dog.getAge() + " years old."
+ " He is a " + dog.getBreed()
+ " When he speaks he says " + dog.speak());
System.out.println("And Finally I have a bird named "
+ bird.getName() + ". He is " + bird.getAge() + " years old."
+ " He has a wingspan of " + bird.getWingspan() + " inches."
+ " When he speaks he says " + bird.speak());
}
}
這裏是我的超
abstract public class Pet {
private String name;
private int age;
// Constructor
public Pet(String petName, int petAge) {
this.name = petName;
this.age = petAge;
}
// Getters
public String getName() { return(this.name); }
public int getAge() { return(this.age); }
// Setters
public void setName(String nameSet) { this.name = nameSet; }
public void setAge(int ageSet) { this.age = ageSet; }
// Other Methods
abstract public String speak();
// toString
@Override
public String toString() {
String answer = "Name: " + this.name + " Age: " + this.age;
return answer;
}
}
這裏是子類中(它們看起來都一樣,並且具有相同的錯誤)
public class Cat extends Pet {
private String color;
// Constructor
public Cat(String petName, int petAge, String petColor) {
super(petName, petAge);
this.color = petColor;
}
// Getters
public String getColor() { return(this.color); }
// Setters
public void setColor(String colorSet) { this.color = colorSet; }
// Other Methods
@Override
public String speak() { return "Meow!"; }
// toString
@Override
public String toString() {
String answer = "Name: " + super.getName() + " Age: "+super.getAge()
+ " Color: " + this.color;
return answer;
}
}
所以發生了什麼是我不能主要的方法找到cat.getColor()
方法od或任何其他子類所特有的。
什麼是錯誤?我相信,自從你做了'貓貓=新貓(...'而不是'貓貓=新貓(...'。 – twain249 2012-04-05 01:46:58
這清除了它,謝謝! – salxander 2012-04-05 01:48:22