tags:

views:

563

answers:

3

Consider the following classes in Java

class A
{
   protected void methodA()
   {
      System.out.println("methodA() in A");
   }

}

class B extends A
{
    protected void methodA() // overrides methodA()
    {
        System.out.println("methodA() in B");
    }

    protected void methodB()
    {
    }
}

public class C extends B // needs the functionality of methodB()
{
    public void methodC()
    {
        methodA(); // prints "methodA() in B"
    }
}

How do I call the methodA() in a from methodC() in class C? Is that possible?

A: 

This looks similar to you're problem

Can you edit B and add a function that calls super.MethodA() ? then call that in C?

Chris Klepeis
+1  A: 

It's not possible.

See http://forums.java.net/jive/thread.jspa?messageID=5194&tstart=0 and http://michaelscharf.blogspot.com/2006/07/why-is-supersuper-illegal.html

ammoQ
It's not possible, directly; there are ways around it.
Dave Jarvis
+1  A: 

You have a few options. If the source code for class B is available, then modify class B. If you don't have the source code, consider injecting code into class B's methodA(). AspectJ can insert code into an existing Java binary.

Change Class B

package com.wms.test;

public class A {
  public A() {
  }

  protected void methodA() {
    System.out.println( "A::methodA" );
  }
}

package com.wms.test;

public class B extends A {
  public B() {
  }

  protected void methodA() {
    if( superA() ) {
      super.methodA();
    }
    else {
      System.out.println( "B::methodA" );
    }
  }

  protected void methodB() {
    System.out.println( "B::methodB" );
  }

  protected boolean superA() {
    return false;
  }
}

package com.wms.test;

public class C extends B {
  public C() {
  }

  protected void methodC() {
    methodA();
  }

  protected boolean superA() {
    return true;
  }

  public static void main( String args[] ) {
    C c = new C();

    c.methodC();
  }
}

Then:

  $ javac com/wms/test/*.java
  $ java com.wms.test.C
  A::methodA

The following does not work:

  protected void methodC() {
    ((A)this).methodA();
  }
Dave Jarvis