0

我有以下两组 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()而是调用了类动物的方法?为什么会这样?

4

3 回答 3

4

#printInfoprivate在子类中并且Animal不能被子类覆盖,您应该将其设为protected.

于 2012-12-29T11:35:50.243 回答
1

私有方法不会在子类中被覆盖。改变

   private void printInfo() { 

  public  void printInfo() {

或者

  protected  void printInfo() {

动物班

于 2012-12-29T11:36:31.513 回答
0

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

请注意,在强制转换之前,使用 instanceof 比较器检查对象使用的 if 语句始终是一个好主意。

于 2012-12-29T11:36:16.017 回答