Victor Cheung
Victor Cheung

Reputation: 153

Inheritance and Private Methods

Given the following block of code:

public class Trial {
    public static void main (String[] args){
        B obj = new B();
        obj.doMethod(); #prints "From A".
    }
}

class A {
    private void method(){System.out.print("from A");}
    public void doMethod(){method();}
}

class B extends A {
    public void method(){System.out.print("from B");}
    public void doMethod(){super.doMethod();}
}

It turns out that the method() from class A is invoked. Why is this?

Upvotes: 1

Views: 96

Answers (6)

Sameera Kumarasingha
Sameera Kumarasingha

Reputation: 2988

method() in class A is private and private methods can't be overriden. And when overriding it's better to use @Override annotion.

class B extends A {

    @Override
    public void method(){System.out.print("from B");} // Compile error
}

A similar thing happens, if you change the method to a static method.

class A {
    public static void method(){System.out.print("from A");}
}

class B extends A {
    public static  void method(){System.out.print("from B");}
}

Upvotes: 0

Chalpat
Chalpat

Reputation: 76

Your code gives simple object creation (B obj = new B();) and a call using super. Super is used like other people mentioned for parent class. Things could have been different if you try something like (A obj = new B();), which is more interesting.

Upvotes: 0

Sumit Singh
Sumit Singh

Reputation: 15906

I think your question is if in class A private void method(){System.out.print("from A");} is private then why is printing "from A" in class B.

Answer is very simple you can't call method() of A class form any other class .But you can call it with object of its own.

when you calls super.doMethod(); then its function of super and method() is its own method so it can call it.

Upvotes: 2

Iswanto San
Iswanto San

Reputation: 18569

You call the doMethod with super keyword. It's means it will call parent implementation More on super keyword

Upvotes: 0

Pradeep Simha
Pradeep Simha

Reputation: 18133

Because, see below:

class B extends A {
    public void method(){System.out.print("from B");}
    public void doMethod(){super.doMethod();}
}

Here in Class B's doMethod() you're invoiking Class A's doMethod() using super.doMethod(). So obviously it's printing Class A's doMethod().

Upvotes: 0

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

You explicitly implement it that way. super calls method from base class which is A

public void doMethod(){super.doMethod();}

So the method chaining is like this:

B.doMethod() -> A.doMethod() -> A.method() -> "from A"

Upvotes: 2

Related Questions