1

I want to call a super class's method through its child class in another class.

For example: a class A and its child class CA, CA override A's method f()

class A{
    f();
}

class CA extends A{
   @Override
   f();
}

a CA's instance in class B:

class B{
    CA mCA = new CA();
}

Is there a way to call the method f() of CA's super class (A) in class B? Like

mCA.super.f();   (I know its wrong)

....

Thanks for any help :)

Allen Mee
  • 51
  • 2
  • 7
  • 6
    You can't - it would violate encapsulation. I'm sure this is a dupe, but it may take a while to find it. – Jon Skeet Sep 23 '14 at 13:06
  • I would guess - but I don't really know and I don't care to take the time to find out - that you could do that through reflection. After all, you can call private methods through reflection. But you should not be doing this. – emory Sep 23 '14 at 13:09
  • @JonSkeet In is a duplicate of e.g. [this question](http://stackoverflow.com/questions/586363/why-is-super-super-method-not-allowed-in-java). – Uwe Plonus Sep 23 '14 at 13:10
  • @UwePlonus: Not quite - this is talking about calling just the super method on an arbitrary object. Put it this way - I can imagine a language where the linked question's request is feasible but this question's request isn't. – Jon Skeet Sep 23 '14 at 13:11

2 Answers2

4

Simply no.

You can call the methods of the object of the class you have.

BTW why do you want to call the method of the super class?

If you need to do this then there is something wrong with your class design. Either CA should create its own method and you can call f() directly in the class CA which in turn calls the method of class A.

Or the overridden method should be compatible with the original implementation. In this case there is no need to call the method of the super class.

Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
  • Thanks Uwe Plonus, It is a indirect way. But maybe the only way to implement this function. Thanks a lot. – Allen Mee Sep 25 '14 at 03:08
  • There's good reason to do this if you need to delegate methods to a proxy, which eventually needs to come back and call the original method. – ddyer Jan 19 '16 at 21:27
1

You would break encapsulation using reflection. Like this ..

PS : This isn't a good practice. This code is just to show that this can be done.

class A {
    public static void f() {
        System.out.println("A");
    }
}

class CA extends A {

    public static void f() {
        System.out.println("CA");
    }
}

class B {
    public static void main(String[] args) throws IllegalArgumentException,
            SecurityException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException { // got genuinely scared here..
        CA mCA = new CA();
        mCA.getClass().getSuperclass().getMethod("f", null).invoke(mCA, null);

    }

}

O/P :

A
TheLostMind
  • 35,966
  • 12
  • 68
  • 104