lowLatency
lowLatency

Reputation: 5654

Java relation b/w parent and child function calling mechanism

I am trying to understand the relation b/w parent and child function calling mechanism, but not got this one

class Parent {
    Parent() {
        greeting();//as we are not calling this on any object, by default it has Parent's greeting method
    }

    void greeting() {
        System.out.println("Greeting Parent");
    }
}

public class SuperConstructor extends Parent {
    public SuperConstructor() {
   //super(); //i know this
        greeting();
    }

    void greeting() {
        System.out.println("Greeting Child");
    }

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

OUTPUT:
Greeting Child, why ? how things work here ?
Greeting Child


OUTPUT (I expected)
Greeting Parent (reason: as the method is there in Parent class)
Greeting Child

Upvotes: 0

Views: 791

Answers (3)

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

Rule of Inheritance: If there is overriding method exists in the child class, it will execute first, always ! And parent's method will be ignored.

So, what happens here ?

>> This new SuperConstructor(); will execute first.

>> Which will create a new class of the child

>> Always remember, if there is no call to super constructor from your child constructor then your JVM will add one implicitly in child class constructor. And that will be the first line to execute.

>> So, your child constructor will make a call to Super(). And your parent consturctor will execute greeting(); As child class has that method overriding, it will execute that instead of parent's. Why ? Because that is our inheritance rule say.

>> After that, child constructor execution will proceed as normal. next in line is greeting();, This will execute again Child's method. Why ? Because our rule of inheritance says so.

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

This is because Parent is calling an overriden method. Make it private and you will get what you expect, private methods are not overridable.

Upvotes: 1

user2374107
user2374107

Reputation:

The reason who see Greeting Child as the Output is because the greeting() method in SuperContructor overrides the greeting() method of the Parent class. When a method Overrides another method, it completely replaces is. Please look at the following post which explains Overriding vs Hiding: Overriding vs Hiding Java - Confused

Upvotes: 1

Related Questions