java 父类调用子类方法_Java从超类调用子类方法

我正在学习Java入门课程,我们才刚刚开始学习继承。我正在完成一项任务,要求我们创建一个具有名称和年龄的“宠物”超类。和三个子类,每个子类都有自己的独特特征(我选择了“狗”,“猫”和“鸟”)。构建完所有这些之后,我们将创建一个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;

}

}

这是子类之一(它们看起来都一样并且有相同的错误)

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()方法,或者无法找到子类独有的其他方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值