In java, Can we override a method by passing subclass of the parameter used in super class method?
NO.
Explanation with example :
Assume we can override a method by passing subclass of the parameter used in super class method.
class A {
public void print(Oject obj)
{
System.out.println(obj.toString());
}
}
class B extends A {
@Override
public void print(String str)
{
System.out.println(str.toString());
}
}
class C extends A {
@Override
public void print(Integer in) {
System.out.println(in.toString());
}
}
class MainTest {
public static void main(String args[])
{
Integer in = new Integer(3);
A a = new B(); // developer by mistake types new B() instead of new C()
a.print(in); // compiler will allow this because class A has print method which can take any subclass of Object type(in this case any class because Object is superclass of all classes in java).
}
}
But think what happens during runtime ?
During runtime, method is called on the actual object to which reference is pointing to. In our case it is pointing to class B.
So JVM will look into class B for method execution and it would be a great shock to JVM because class B does not have a overriden
method with signature public void print(Integer in) and it will fail at runtime.
The consequence of this is application will crash at runtime rather than compile time.
Overriding rules in Java :
- Arguments must be the same & return types must be compatible
- The method can't be less accessible
=============================
In your example what happens is :
During compile time : compiler makes sure that eat method can be called on reference type(which is Aniaml class).
Since Animal class has a method public void eat(Food food) which can take any Food type and subclass of
Food type as input parameter(polymorphism), compilation passes.
In general, compiler guarantees that particular method is callable for a specific reference type.
During run time : Actual method called is, most specific version of the method for that object type(Dog class).Since
JVM is not able to find the overriden method i.e with the same method name and same argument type declared
in sub class (Dog class), it checks its superclass(Animal class) and finds the method and executes.
public void eat(Food food) and
public void eat(Flesh flesh)
are not same from the perspective of overriding methods.
In general, when you call a method on an object reference, you're calling the most specific version of the method for that
object type during runtime. But if it doesn't find one it will go up the hierarchy.Worst case Super class will definitely have
the method implementation otherwise compilation wont pass.