-1

In this code:

public abstract class Bird {
    private void fly() {
        System.out.println("Bird is flying");
    }

    public static void main(String[] args) {
        Bird bird = new Pelican();
        bird.fly();
    }
}

class Pelican extends Bird {
    protected void fly() {
        System.out.println("Pelican is flying");
    }
}

Please explain why the output of this is "Bird is flying", since private members are not inherited and I have a Pelican instance in Bird?

CT Hall
  • 667
  • 1
  • 6
  • 27
Ivan Karotki
  • 139
  • 2
  • 15
  • You can't override a `private` method. For some reason I'm surprised this compiles at all. – Federico klez Culloca Apr 19 '19 at 14:49
  • You are not overriding fly method from inherited class. – Rahul Apr 19 '19 at 14:50
  • it's not about i'm overriding something or not, it's about how Pelican instance gets private code of his parent... – Ivan Karotki Apr 19 '19 at 15:10
  • summarize all comments i assume - Bird reference do not let Pelican instance to reach his own method fly(), and only because main() method placed in Bird-class private Bird-class method fly() is invoked. Also if access modifier in parent class would be protected then parent method would be overriden and child version would be invoked. Am i correct? – Ivan Karotki Apr 19 '19 at 15:56

1 Answers1

-1

When the reference type is Bird, the object can only access the methods within the class Bird, despite being of type Pelican. The reference type always means a constraint and cannot access fields of e.g. subclasses.

Tasha
  • 9
  • 5
  • the reference is assigned of Pelican – Hasnain Ali Bohra Apr 19 '19 at 14:54
  • Bird bird = new Pelican(): bird is the reference to the object and it's of type Bird. Pelican is the type of the object that is stored in memory. There's a difference between reference and object. – Tasha Apr 19 '19 at 14:55
  • Yes `bird` is defined as a `Bird`, but that's not how polymorphism usually works. In this case it does because the method of the base class is defined as `private`, but that's not the norm. If that method was `public` or `protected` it would have printed `Pelican is flying` even if `bird` is defined as a `Bird` – Federico klez Culloca Apr 19 '19 at 14:58
  • I see what you're saying. Sorry about that, I'll delete to avoid further confusion. – Tasha Apr 19 '19 at 15:00
  • Concept 1 :- when you make the private methods it is access only within the class. it can not inherited. Concept 2:- here the code private void fly() { System.out.println("Bird is flying"); } can not inherited. so the code in the `Pelican` class is not inherited and it is treated as `Pelican` class own method. protected void fly() { System.out.println("Pelican is flying"); } – Hasnain Ali Bohra Apr 19 '19 at 15:01
  • Thanks alot for clarifying! – Tasha Apr 19 '19 at 15:10