Java 从超类调用子类的重写方法出错?
我有以下两组Java代码。第一个可行,但第二个不行Java 从超类调用子类的重写方法出错?,java,superclass,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()
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.");
}
}
这里不使用animalList.get0.printInfo调用重写的方法printInfo,而是调用类animal的方法?为什么会发生这种情况?printInfo在Animal中是私有的,不能被子类覆盖,您应该使其受到保护 printInfo在Animal中是私有的,不能被子类覆盖,您应该使其受到保护 尝试将对象强制转换为子类,即FishesanimalList.get0.printInfo
注意:在强制转换之前,最好使用instanceof comparator检查使用if语句的对象的类型。尝试将对象强制转换为子类,即FishesanimalList.get0.printInfo 注意:在强制转换之前,最好使用instanceof comparator检查使用if语句的对象的类型。在子类中不会重写私有方法。 改变
private void printInfo() {
到
或
在动物类中。子类中不重写私有方法。
改变
private void printInfo() {
到
或
在Animal类中。+1此外,每当您打算重写一个方法时,最好使用@Override注释-在这种情况下,您的IDE和/或java编译器将标记此错误。它已解决,但通常是这样吗?还有什么可能?超类中的方法的修饰符应该是什么,以便可以在子类中重写它?@user1837224对应该在子类中重写但在外部不可见的方法使用protected,每当您打算重写一个方法时,最好使用@Override注释——在这种情况下,您的IDE和/或java编译器会标记这个错误。它已经解决了,但通常是这样的吗?还有什么可能?超类中方法的修饰符应该是什么,以便可以在子类中重写它?@user1837224对应该在子类中重写但在外部不可见的方法使用protected。
protected void printInfo() {