0

How to call parent overridden method. Because when I call same method, overridden method of child class is called. But what if i want to call parent method explicitly through object, how can i do it? I want "hello B" as output.

   class B
{
B()
{
    System.out.println("B");
}
void display()
{
    System.out.println("hello B");
}
}

class A extends B
{ 
 A()
{
    System.out.println("A");
}
void display()
{
    System.out.println("hello A");

}
public static void main(String[] args)
{

    A a= new A();
    a.display();
}           
}

output:

B
A
hello A

expected:

B
A
hello B
  • You either create a `B` object or add a method in `A` that calls `super.display()`. – Sweeper Feb 04 '18 at 12:38
  • Possible duplicate of [Can java call parent overridden method in other objects but not subtype?](https://stackoverflow.com/questions/1032847/can-java-call-parent-overridden-method-in-other-objects-but-not-subtype) – Sharon Ben Asher Feb 04 '18 at 12:46
  • @ArifMustafa No, that would destroy the purpose of inheritance. – bcsb1001 Feb 04 '18 at 13:09

2 Answers2

0

The instance you created is an A instance. Wherever A has an implementation for a method like display(), that one (A.display() ) will be called and get control. Always.

A.display() can decide that it'll use the parent's implementation by calling super.display() somewhere in its body. You can't do it from outside, only the A.display() method itself can do so.

When you design a class, you decide how its instances will react to method calls. If you override a method, you have a reason to do so: with a child instance, the parent implementation won't do what the method name demands. So, were it possible to call the parent method from outside, things would generally go wrong.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
0

Try like this:

public class A extends B {

    public A() {
        System.out.println("A");
    }

    void display() {
        System.out.println("hello A");
    }

    void displayB() {
        super.display();
    }

    public static void main(String[] args) {

        //first it will go to A constructor
        //from A, constructor first it will execute the super();
        //due to inheritance concept, execute B block statements //print "B"
        //then it will execute the A block statements //print "A"
        //after that it will execute the method, which will print the parent class method
        new A().displayB();
    }

}
ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
  • hello sir, actually i think that the suggestion u have made is about to create another method which is calling parent method. But i want to know that java has any method like a.super.display() to call same method of parent class about which I am not aware of? – Abhijeet Ohol Feb 04 '18 at 23:34