次の2セットのJavaコードがあります。最初のものは機能しますが、2 つ目は機能しませんか?
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.");
}
}
2番目のコードセットは
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()
代わりに動物クラスのメソッドが呼び出されますか? なぜこれが起こっているのですか?