简体   繁体   English

父方法中的重写方法调用

[英]Overridden method call in parent method

Considering the following:考虑到以下几点:

public class Child extends Parent{
  public boolean isMeh(){
    return true;
  }

  public void childMethod() {
    System.out.println("child: "+isMeh());
  }

  public static void main(String... args){
    Child child = new Child();
    child.parentMethod();
    child.childMethod();

  }

}

class Parent{
  public boolean isMeh(){
    return false;
  }

  public void parentMethod() {
    System.out.println("parent: "+isMeh());
  }
}

Output:输出:

parent: true
child: true

It is pretty obvious when isMeh() is called within Child class, it calls the overridden method.在 Child 类中调用 isMeh() 时很明显,它调用了重写的方法。

But when the overriden method is called within a method of the parent object, it still calls the child object's method.但是当在对象的方法中调用被覆盖的方法时,它仍然调用子对象的方法。

I see that we create one child object and parentMethod is just inherited so when we call isMeh() it calls the available(overridden) one.我看到我们创建了一个子对象,而 parentMethod 只是继承的,所以当我们调用 isMeh() 时,它会调用 available(overridden) 一个。

What would be the reason for this implementation in java?在java中实现这个的原因是什么?

Any class in an inheritance hierarchy of Parent , be it a Child , a Parent , or some Grandchild deriving from them, has exactly one implementation of the method called isMeh .在继承层次结构的任何类Parent ,无论是Child ,一个Parent ,或者一些Grandchild从他们那里获得,有且只有一个实现调用的方法的isMeh When Child overrides isMeh of Parent with its own implementation, it replaces the implementation;Child用自己的实现覆盖Parent isMeh时,它替换了实现; as far as the Child is concerned, the implementation in the Parent no longer applies * .Child而言, Parent的实现不再适用*

When you instantiate Child and call its parentMethod , the method has access to only one method isMeh - that is, the implementation provided by the Child .当您实例化Child并调用其parentMethod ,该方法只能访问一个方法isMeh - 即Child提供的实现。 That is why you get the behavior that you describe.这就是为什么你会得到你所描述的行为。

This behavior allows for very nice patterns: for example, you can write a "partial implementation" of a method in the parent by relying on "plug-in" functionality in the child class provided through overrides.这种行为允许非常好的模式:例如,您可以通过依赖通过覆盖提供的子类中的“插件”功能在父类中编写方法的“部分实现”。 This technique is known as Template Method Design Pattern .这种技术被称为模板方法设计模式

* although Child retains an ability to call Parent 's isMeh explicitly. *尽管Child保留了显式调用ParentisMeh的能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM