开发者

How to call base class method with derived class Object when that method overridden in derived class?

class A 
{
  public void m1()
  {
    System.out.println("hi-base class");
  }
}

class B extends A
{
  public void  m1()开发者_如何学运维
  {
    System.out.println("hi-derived ");
  }

  public static void main(String args[])
  {
    B b1=new B();
  }
}

In this i want to invoke base class m1 method by using Derived class object without using the super


You would need to construct an object of type A. You have overridden method m1 in the derived class, and so any calls to m1 on an object that was created as a B will have the B version of m1 invoked. Without using super, there's no way to instruct the compiler to make the non-virtual call to the base-class version.


Are you just looking for super.m1();? This will invoke the immediate parent's method.

However, you cannot instantiate an object of type B from outside of B and use this.

You cannot do:

B value = new B();
value.super.m1(); // call A's implementation

However, you could do this within B:

@Override
public void m1()
{
    System.out.println("hi from B");
    super.m1();
}

public void useAM1()
{
    super.m1();
}

Of course, when you start to provide workarounds to get at functionality from A, then it sounds like you are abusing inheritance, or at least should have used an instance of A to begin with.

Interestingly, in C++ you could do this: value->A::m1();. Fortunately, there is no equivalent in Java.


In short you cannot do it -- virtual dispatching would delegate the call to the referred.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜