假设我有以下课程
Class Parent{ public void test(){ System.out.println("Parent"); } } Class Child extends Parent{ public void test(){ System.out.println("Child"); } } Parent parentE = new Child(); parentE.test(); ((Parent)parentE).test();输出是:
Child Child但是如何使用parentE引用在这种情况下运行父方法?
Suppose I have the following classes
Class Parent{ public void test(){ System.out.println("Parent"); } } Class Child extends Parent{ public void test(){ System.out.println("Child"); } } Parent parentE = new Child(); parentE.test(); ((Parent)parentE).test();Output is:
Child ChildBut how can I run parent method in this case using parentE reference?
最满意答案
这是多态性的一个关键特征。
您实例化的对象是Child的实例。 调用该对象的test() 总是会导致调用Child的(重写) test() ,即使您已将该实例分配给Parent类型的变量也是如此。
简而言之,这是您可以实现更具体的行为,同时只需使用声明为超类类型的变量引用该对象。 通常,它与基类一起使用,仅为子类提供抽象方法以覆盖。
初学者书中的一个小例子通常涉及动物或汽车:
public abstract class Animal { private final String name; public Animal(String name) { this.name = name; } public void printName() { System.out.println(name); } // more animal general stuff followed by: public abstract void makeSound(); } public class Dog extends Animal { public Dog() { super("Dog"); } @Override public void makeSound() { System.out.println("Woof!"); } } List<Animal> aList = new ArrayList<Animal>(); aList.add(new Dog()); aList.add(new Cat()); // etc for (Animal a : aList) { a.printName(); a.makeSound(); // calls each subclasses' "makeSound()" }除非您实例化Parent或从Child的方法中调用super.test() ,否则不能调用Parent的test() 。
(我其实在想我能找到一个很好的副本,提供了一个不错的答案,但我不能)
This is a key feature of polymorphism.
The object you instantiated is an instance of Child. Calling that object's test() is always going to result in the Child's (overridden) test() being called, even if you've assigned that instance to a variable of Parent type.
In short, this is how you can achieve more specific behavior while only having to reference the object using a variable declared a superclass type. Often this is used in conjunction with the base class only providing an abstract method for the subclasses to override.
A trivial example in beginner's books usually involves animals or cars:
public abstract class Animal { private final String name; public Animal(String name) { this.name = name; } public void printName() { System.out.println(name); } // more animal general stuff followed by: public abstract void makeSound(); } public class Dog extends Animal { public Dog() { super("Dog"); } @Override public void makeSound() { System.out.println("Woof!"); } } List<Animal> aList = new ArrayList<Animal>(); aList.add(new Dog()); aList.add(new Cat()); // etc for (Animal a : aList) { a.printName(); a.makeSound(); // calls each subclasses' "makeSound()" }You can't call the Parent's test() unless you instantiate a Parent or call super.test() from within a method in Child.
(I was actually thinking I could find a good duplicate for this that provided a decent answer, but I couldn't)
更多推荐
发布评论