【问题标题】:Calling some line of parent methods and then call child method.. possible? ways?调用一些父方法,然后调用子方法..可能吗?方法?
【发布时间】:2014-05-21 05:20:34
【问题描述】:

请看下面的代码

Class A    
{
    method1 ()
    {
        code;
        code;//I want to run the code at this point and then resume with the child class method 
        code;//dont want this code If called from derived class
    }
}
Class B:A
{
    method1()
    {
        super();// Calling method1 of class A
    }
}

请建议我有多少种方法可以实现这一目标。我不想重新编写与 A 类的方法 1 中相同的代码。

【问题讨论】:

  • 为什么?你的意思是“super.method1();”对吗?
  • 我认为这做不到。
  • @ElliottFrisch 否则我将不得不在 B 类中重新编写 A 类代码

标签: oop inheritance code-reuse


【解决方案1】:

这是你想要达到的目标吗?

Class A{
    method1 (){
        code;
        method2(); // common code
        code;//dont want this code If called from derived class
    }
    method2(){
        code;//I want to run the code at this point and then resume with the child class method 
    }
}

Class B:A{
    method1(){
        super.method2();// Calling method2 of class A
    }
}

一般来说,如果你想重用/重写一个方法的片段,可以考虑将它分成子例程,这些子例程可以从子类中独立调用/重写。这在某种程度上类似于template method 模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多