从超类调用子类方法

29

我正在学习Java入门课程,我们刚刚开始学习继承。我在做一个任务,要求我们创建一个"Pet"超类,包括名称和年龄;还有三个子类,每个子类都有自己独特的特征(我选择了"Dog","Cat"和"Bird")。在我们构建完所有这些后,需要创建一个主类来测试一切,这就是我遇到问题的地方。我试图在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()方法,或者任何子类独有的其他方法。

5个回答

37

当你将一个变量声明为超类类型时,你只能通过该变量访问(公共的)超类方法和成员变量。

Pet cat = new Cat("Feline",12,"Orange"); 
cat.getName(); // this is OK
cat.getColor(); // this is not OK, getColor() is not in Pet
为了访问具体类中的方法(在此例中为Cat),您需要将变量声明为派生类。
Cat cat = new Cat("Feline",12,"Orange"); 
cat.getName(); // OK, getName() is part of Cat (and the superclass)
cat.getColor(); // OK, getColor() is part of Cat

或者将其转换为您已知或怀疑的具体类型

Pet cat = new Cat("Feline",12,"Orange"); 
((Cat)cat).getName(); // OK (same as above)
((Cat)cat).getColor(); // now we are looking at cat through the glass of Cat

你甚至可以将这两种方法结合起来:

Pet pet = new Cat("Feline",12,"Orange"); 
Cat cat = (Cat)pet;
cat.getName(); // OK
cat.getColor(); // OK

5
由于这是更完整和完全正确的版本,所以我删除了我的版本。 - JamesSwift
这个救了我的命。 - Все Едно
我们不能访问超类的受保护方法和成员变量吗? - Beginner
@初学者 你可以在子类中访问,但只能在子类内部访问。上面的例子是假设从外部访问(例如一个不相关的类或非成员函数)。 - Attila

1
在这里,您试图使用子类方法(Cat)创建超类类型对象(cat),这是不可能的。这违反了继承规则。

Pet cat = new Cat("Feline", 12, "Orange");


1
Pet cat = new Cat("Feline",12,"Orange");
^^^
This is the error.

Pet没有名为getColor()的方法

您需要执行以下操作:

Cat cat = new Cat(...);

1

当您执行以下操作时:

 Pet cat = new Cat("Feline",12,"Orange");

编译器将变量cat视为Pet。因此,您无法使用Cat类的特定方法。
您必须将cat声明为Cat类型以解决问题。
敬礼。

0
您还可以在Pet类中添加这些空方法:
public String getColor() { }
public String setColor() { }
public String speak() { }

通过这种方法,您可以从Pet对象调用此方法,而无需将其转换为Cat。一旦调用它,Cat的方法将覆盖超类的一个方法。 这种技巧的缺点是,您必须在超类中声明每个您打算从子类调用的方法的空方法,如果要添加多个方法,则可能会变得混乱。因此,只对许多不同子类中将使用的方法进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接