-1

Imagine I have a class like this :

public class Alpha {

   int i = 5;

   @Override
   public String toString() {
       return "Alpha [i=" + i + "]";
   }

   public String superToString() {
       return super.toString();
   }

}

then I do in a main:

Alpha o = new Alpha();
System.out.println(o.toString()); // display ==> Alpha [i=5]
System.out.println(o.superToString()); // display ==> pojos.Alpha@77468bd9

all is ok. now, imagine i don't have my method called superToString() in Alpha. is there a way to call method of parent of my Alpha instance ? (in this example, toString of Object)

Snow
  • 3,820
  • 3
  • 13
  • 39
electrode
  • 205
  • 1
  • 4
  • 16

2 Answers2

3

If a child class overrides a method, it is no longer possible to call the overridden method from another class. There is no way around this.

Using reflection won't help:

var alpha = new Alpha();
var aMethod = alpha.getClass().getSuperclass().getMethod("toString");
System.out.printf("For method %s() in super class %s the call still results in \"%s\"%n",
        aMethod.getName(), aMethod.getDeclaringClass().getSimpleName(),
        aMethod.invoke(alpha));

results in:

For method toString() in super class Object the call still results in "Alpha [i=5]"

The problem is that any mechanism that would allow you to do this is breaking encapsulation and abstraction at a fundamental level.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

This is called method overriding by sub class. Class 'Alpha' has overridden method 'toString'. Class Object is default super class if none specified.

You can capture toString of super in overridden method and append/prepend it to response

@Override
public String toString(){
  String superToString = super.toString();
  return superToString + " -> Alpha [i=" + i + "]";
}
Peeyush
  • 422
  • 3
  • 13
  • you didn't understand. i know all about what you explain but i just don't want to do that. Imagine Alpha can not be editable and so, we can' t use the keyword super in this 'child class'. The question is : when i 'use' Alpha, can i force the toString() of the Parent (Object) ? – electrode Dec 22 '19 at 01:09
  • You're kind of contradicting your own post here. You said you had a class and showed its source, so clearly you conrol that source code. If you don't, please update your post with more details. – Mike 'Pomax' Kamermans Dec 22 '19 at 01:41
  • You can't force toString() of parent from child class' instance. As explained in other answer reflection is not helpful either. This is one way capture it if you control child class' source. – Peeyush Dec 22 '19 at 19:58