0

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.

Jerrick
  • 1
  • 1
  • If you define a `private` `method` in a class you will not be able to access it from any other class, and *even a subclass* **can't override or access this method**. So in your case here, if you set `hasHorns()` as private in `Deer` class it will not be overriden in the `Reindeer` subcalss that's why you will get `true`, but if you change its access modifier it will be overriden by the subclass so if you call it you will get `false`. – cнŝdk Jun 09 '15 at 16:05

1 Answers1

1

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.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332