2

I Have Parent Child relationship class and one override method i want to display only parent class method.

class Parent{
    public void display(){
        System.out.println("Parent class display....");
    }
}
class Child extends Parent{
    public void display(){
        System.out.println("Child class display....");
    }
}

public class Demo {
    public static void main(String... args)  {
        Parent parent = new Child();
        parent.display();
    }
}

Desired Output :- Parent class display....

Is this Possible ?

user3297173
  • 111
  • 1
  • 1
  • 8

2 Answers2

1

Directly, no. To give access to the superclass implementation, you have to expose it somehow, otherwise it it is not visible externally at all. There are a couple ways you can do this.

Child Method Calling Super

You could add a method to Child that calls Parent's implementation of display():

public void superDisplay()
{
    super.display();
}

You would have to cast your reference to make the call:

((Child)parent).superDisplay();

Note that adding a method to Parent that calls display() would not help because it would call Child.display() for Child instances because of polymorphism.

Something similar to this technique is commonly used when extending swing components, where the child's implementation of paintComponent() often invokes super.paintComponent().

Reflection

While often a kludge indicating bad design, reflection will give you exactly what you want. Simply get the display method of the Parent class and invoke it on a Child instance:

try {
    Parent.class.getMethod("display").invoke(parent);
} catch(SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | ex) {
    // oops!
}
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
-1

If you are simply looking for a way, you can declare your display() method to be static in both classes.

public static void display(){
}
Sabir Khan
  • 9,826
  • 7
  • 45
  • 98