Sarabjeet
Sarabjeet

Reputation: 274

Why super class method being called here?

this is my code

class Hello{
    void method(){
        System.out.println("super method");
        meth();
    }
    private void meth(){
        System.out.println("sup meth");
    }
}
public class HelloWorld extends Hello{
    //@Override - would fail as meth is private in Hello
    protected void meth(){
        System.out.println("sub meth");
    }
    protected void method(){
        super.method();
    }
     public static void main(String []args){
        new HelloWorld().method();
     }
}

the returned result is

super method
sup meth

but why ? shouldn't it instead print

super method
sub meth 

if I were to write meth method as public in Hello and override it in HelloWorld

result wud be abovementioned one. meth invocation from method still invokes meth of sub class , even though the meth invocation is inside super class , lexically speaking ! So why different behavior when meth is private ?

_____________Edit_____________

Had the code been something like this

class Hello{
    void method(){
        System.out.println("super method");
        meth();
    }
    protected void meth(){
        System.out.println("sup meth");
    }
}
public class HelloWorld extends Hello{
    //@Override - would fail as meth is private in Hello
    protected void meth(){
        System.out.println("sub meth");
    }
    protected void method(){
        super.method();
    }
     public static void main(String []args){
        new HelloWorld().method();
     }
}

the o/p would be

super method
sub meth

So, even though method in super class Hello is invoking meth , actually sub class's meth is being called . So , method invocation is not in the lexical sense ! i.e even if it seems the super class's meth will be invoked, its actually subclass's becoz subclass instance invoked method in the first place. why things differnt when meth private in super class

Upvotes: 0

Views: 225

Answers (3)

Cat Snacks
Cat Snacks

Reputation: 96

The Super class is calling meth() from itself, and thus, it is looking for this.meth(). The super doesn't even know about the subclass's meth() because 1) It is in a subclass, 2) The subclasses method is private.

I would recommend reading up on inheritance: Java Inheritance

Upvotes: 0

christopher
christopher

Reputation: 27346

Your method meth() is private and the subclass has no access to it.

Upvotes: 1

thatidiotguy
thatidiotguy

Reputation: 8991

You cannot override a private method as the compiler tells you. So the only meth() the super class knows about is its own.

You cannot override a private method as it is internal to the class, so its subclasses do not even know its super's private methods exist.

Upvotes: 3

Related Questions