Inheritance Hidden Method java

414 views Asked by At

Hi I came upon with a snippet of this code on a book. But somehow I could not fully understand how java uses the private method over the public

package com.toro.employee2;

public class Deer {
    public Deer() {
        System.out.print("Deer");
    }

    public Deer(int age) {
        System.out.print("DeerAge");
    }

    private boolean hasHorns() {
        return false;
    }

    public static void main(String[] args) {
        Deer deer = new Reindeer(5);
        System.out.println("," + deer.hasHorns());
    }
}

class Reindeer extends Deer {
    public Reindeer(int age) {
        System.out.print("Reindeer");
    }
    public boolean hasHorns() {
        return true;
    }
}

The output is DeerReindeer,false My questions is:

When I change the Deer class hasHorns() method to other access modifier other than PRIVATE it will use the Reindeer class hasHorns() method thus returning true but if the Deer class hasHorns() method uses the PRIVATE access modifier it will return false instead.

It would be great if you could explain how this works.

1

There are 1 answers

0
Luiggi Mendoza On

private methods are not inherited and not overridden. Thus, when you call deer.hasHorns(), the method executed is Deer#hasHorns. In fact, if you move the main method from Deer to Reindeer or another class, that piece of code will fail.