从超类错误中调用子类的重写方法?

时间:2012-12-29 11:29:03

标签: java superclass

我有两套Java代码。第一个有效但第二个有效吗?

package animal;

import javax.swing.JOptionPane;
import java.util.ArrayList;

public class Animal {

    public static void main(String[] args) {
        Animal createAnimals = new Animal();
        createAnimals.printInfo();
        String userInput = createAnimals.userInputHandle();
        Fishes a = new Fishes();

        switch (userInput) {
            case ("shark"):
                a.printInfo();
        }
    }

    private void printInfo() {
        JOptionPane.showMessageDialog(null, "Welcome to Animal Kingdom.");
    }

    private String userInputHandle() {
        String userInput;
        userInput = JOptionPane.showInputDialog("Select animal from the "
                + "following list"
                + "\n1.Dog\n2.Cat\n3.Snake\n4.Frog"
                + "\n5.Human\n6.Shark\n7.Sea Gulls");
        userInput = userInput.toLowerCase();

        return userInput;
    }
}

class Fishes extends Animal {

    public void printInfo() {
        JOptionPane.showMessageDialog(null, "Shark belongs to Fish subclass of Animal kingdom.");

    }
}

和第二组代码是

package animal;

import javax.swing.JOptionPane;
import java.util.ArrayList;

public class Animal {

    public static void main(String[] args) {
        Animal createAnimals = new Animal();
        createAnimals.printInfo();
        String userInput = createAnimals.userInputHandle();

        ArrayList<Animal> animalList = new ArrayList<Animal>();

        animalList.add(new Fishes());

        switch (userInput) {
            case ("shark"):
                animalList.get(0).printInfo();
            case ("sea gulls"):
        }
    }

    private void printInfo() {
        JOptionPane.showMessageDialog(null, "Welcome to Animal Kingdom.");
    }

    private String userInputHandle() {

        String userInput;
        userInput = JOptionPane.showInputDialog("Select animal from the "
                + "following list"
                + "\n1.Dog\n2.Cat\n3.Snake\n4.Frog"
                + "\n5.Human\n6.Shark\n7.Sea Gulls");
        userInput = userInput.toLowerCase();

        return userInput;
    }
}

class Fishes extends Animal {

    public void printInfo() {
        JOptionPane.showMessageDialog(null, "Shark belongs to Fish subclass of Animal kingdom.");

    }
}

此处未使用printInfo调用重写的方法animalList.get(0).printInfo(),而是调用类动物的方法?为什么会这样?

3 个答案:

答案 0 :(得分:4)

#printInfoprivate中为Animal且无法被子类覆盖,您应该将其设为protected

答案 1 :(得分:1)

子类中

私有方法未被重写。 改变

   private void printInfo() { 

  public  void printInfo() {

  protected  void printInfo() {

动物类

答案 2 :(得分:0)

尝试将对象转换为子类,即(Fishes)animalList.get(0).printInfo();

注意在转换之前,最好使用instanceof比较器检查对象使用if语句的类型。