class Sample1 {
    Sample1() {System.out.println("Sample1 const"); }
    void doStuff(){System.out.println("sample1 dostuff"); }
}

class Sample2 extends Sample1 {
    Sample2() {System.out.println("Sample2 const"); }
}

public class Sample3 extends Sample2 {
    Sample3() {System.out.println("Sample3 const"); }
    public static void main(String r[]) {
        new Sample3().go();
    }

    void go() { super.doStuff(); }
}

The output is:
Sample1 const
Sample2 const
Sample3 const
sample1 dostuff

My doubt is that super.doStuff() should invoke Sample2 method doStuff() if present. Why has it "propagated" upwards? I thought that happened only with no-arg super() being put implicitly (if not present) as first line of constructor.

Recommended Answers

All 4 Replies

what is "propagating upwards"? do you mean, why does it call the method in Sample1?

Yeah, sorry for loose words. I mean to ask doStuff() is not defined in Sample2 where it checks according to super.doStuff(), then why does it go to Sample1 on it's own?

Is there an invisible no-arg super inserted for method call also in a inheritance hierarchy?

I hope my doubt is clear now.

it's not "on it's own". the method doStuff is actually defined in Sample2.

I'm not sure how far your knowledge about inheritance goes, so I'll try to put it simple.

a class extending another class inherits every member in that parent class. it is possible to re-define that member in the child class, but this is not needed to do, unless the implementation is different.

so this:

class Sample1 {
    Sample1() {System.out.println("Sample1 const"); }
    void doStuff(){System.out.println("sample1 dostuff"); }
}
class Sample2 extends Sample1 {
    Sample2() {System.out.println("Sample2 const"); }
}

is actually the exact same as:

class Sample1 {
    Sample1() {System.out.println("Sample1 const"); }
    void doStuff(){System.out.println("sample1 dostuff"); }
}
class Sample2 extends Sample1 {
    Sample2() {System.out.println("Sample2 const"); }
    void doStuff(){System.out.println("sample1 dostuff"); }
}

if you call a method in the child class that isn't specifically defined in the child class, it will go through the inheritance hierarchy, all up to the Object class if need be, to find an implementation.

so when you called 'doStuff' on an instance of Sample2, it just ran the implementation of the method defined in the first parent class in the line, being Sample1, because that is the one inherited by Sample2

Great just as I expected. Thanks stultuske!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.