I was playing around with simple overloading overriding rules and found something interesting. Here is my code.
package com.demo; public class Animal { private void eat() { System.out.println("animal eating"); } public static void main(String args[]) { Animal a = new Horse(); a.eat(); } } class Horse extends Animal { public void eat() { System.out.println("Horse eating"); } }
This program outputs the below.
animal eating
Here is what I know:
private void eat()
method, it is not definitely going to be accessed in a subclass, so the question of method overriding does not arise here as JLS defines it clearly.public void eat()
method from the Horse classAnimal a = new Horse();
is valid because of polymorphism.Why is a.eat()
invoking a method from the Animal
class? We are creating a Horse
object, so why does the Animal class' method get called?
Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.
The overridden method shall not be accessible from outside of the classes at all. But you can call it within the child class itself. to call a super class method from within a sub class you can use the super keyword.
Methods marked private
can't be overridden in subclasses because they're not visible to the subclass. In a sense, your Horse
class has no idea whatsoever that Animal
has an eat
method, since it's marked private
. As a result, Java doesn't consider the Horse
's eat
method to be an override. This is primarily designed as a safety feature. If a class has a method it's marked private
, the assumption is that that method is supposed to be used for the class internals only and that it's totally inaccessible to the outside world. If a subclass can override a private
method, then it could potentially change the behavior of a superclass in an unexpected way, which is (1) not expected and (2) a potential security risk.
Because Java assumes that a private
method of a class won't be overridden, whenever you call a private
method through a reference of some type, Java will always use the type of the reference to determine which method to call, rather than using the type of the object pointed at by that reference to determine the method to call. Here, the reference is of type Animal
, so that's the method that gets called, even though that reference points at a Horse
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With