I'm new to Java Programming and learning polymorphism.
__EDIT__
As per the answers I received from everyone,I have code:
Here I'm typecasting my Derived
object (obj
) to Base
type and then calling method()
.
public class Tester {
public static void main(String[] args) {
Base obj=(Base)new Derived();
obj.method();
}
}
class Base{
public void method(){
System.out.println("In Base");
}
}
class Derived extends Base{
public void method(){
System.out.println("In Derived");
}
}
Output I'm getting is: "In Derived".
So after typecasting my object should become of type Base
referenced by Base
type.
But it's not happening? Why?
Does typecast work on child->parent conversion or it has no effect here?
Base obj=new Derived();
In the above statement, the reference part points to type
Base
. This is how the compiler identifies which class to consider. But your code will create an error. Let me explain the structure of the above statement before explaining why will it show an error.Structure of the above statement:
Base obj
.Instantiation: The new keyword is a Java operator that creates the object/allocates space in the memory.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Since,
Derived
is a sub-class ofBase
, you are allowed to call the constructor in theDerived
class. This is how inheritance and polymorphism works.Okay, Now let us go back to the error part. The
obj.method()
in your code is looking for a functionmethod()
inBase
class but themethod(int a)
function inBase
class requires an argument of type integer to be passed. So for the code to work, the calling statement has to be something likeobj.method(5)
.This statement works because the calling statement is actually passing 5 to the function.There is an easy fix for your code:
Derived obj=new Derived();
Have you noticed?
Derived
.Why does that work?
method()
function in yourDerived
class which doesn't require an integer argument.There is one more amazing fact about inheritance in Java:
The above statement means the following code will work:
You must be wondering-How come this code works even though
method()
inDerived
requires no argument. In fact,Derived
has nomethod(int a)
.Yes,
method(int a)
also belongs toDerived
since it's a sub-class ofBase
.But How does the code mentioned below work?
Simple, the JVM looks for the
method(int a)
in classDerived
and it finds the function sinceDerived
has inherited the function fromBase
class. Remember this too, the sub-class also has a privilege to over-ride a method in super class. This means that you can addmethod(int a)
function in classDerived
which over-rides the original method inherited fromBase
.How inheritance works?
obj.method(5)
in the above code, the JVM first looks for any over-ridden method of the same type inDerived
. If it does not find any over-ridden method, it moves up in theinheritance hierarchy chain
to the super class and looks for the same method. But the reverse is not the true.