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