私は入門Javaコースに入っており、継承について学習し始めました。私は、名前と年齢の「ペット」スーパークラスを作成するように求めています。 (私は "Dog"、 "Cat"、 "Bird"を選択しています)それぞれ独自の特性を持つ3つのサブクラスがあります。これらをすべて構築したら、すべてをテストするためのMainクラスを作成する必要があります。ここで問題に取り組んでいます。私はこれらのユニークな形質のためにget
メソッドをMain
の中で呼び出そうとしていますが、スーパークラスにあるメソッドしか見つからないようです。ここでスーパークラスからサブクラスメソッドを呼び出す
はメインクラスである:ここでは
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;
}
}
であり、ここでのサブクラスの1(彼らはすべて同じに見えるし、同じエラーを持っている)
です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、またはサブクラスに固有のその他のサブクラスのいずれかです。
エラーは何ですか?私はあなたが '' Cat cat = new cat(... 'の代わりに' 'cat cat = new cat(...')をしたので、あなたがキャストしなければならないと信じています。 – twain249
これで解決しました。ありがとうございます! – salxander