Reputation: 1809
my code is
class Alpha
{
public void foo()
{
System.out.print("Alpha ");
}
}
class Beta extends Alpha
{
public void foo()
{
System.out.print("Beta ");
}
public static void main(String[]args)
{
Alpha a = new Beta();
Beta b = (Beta)a;
a.foo();
b.foo();
}
}
Output:-
Beta Beta
i am new to java and this kind of instantiation i have come across for the first time and thats why i am not able to understand why the output is not
Alpha Beta
if 'a' is the object of class Alpha then why not Alpha's method is being called?
Please help me out.
Upvotes: 1
Views: 93
Reputation: 153
In java, methods are virtual by default. When deciding what method to actually invoke, the type of the underlying object matters, not the type of the reference to the object.
Upvotes: 0
Reputation: 1184
You have just one object of type Beta. Casting an object does not make java to use the parent method.
Upvotes: 0
Reputation: 5258
When parent class variable refers child class object, the reference will call child methods.
Upvotes: 0
Reputation: 143886
Casting or referencing an Object as its superclass doesn't un-override methods. The foo()
method is still being called on a Beta
Object, even if you are originally referencing it as an Alpha
Object.
Upvotes: 1
Reputation: 915
The object that is created is a type Beta
, because that's how it was created by new
. So, when foo()
is called, it's working on a Beta
object no matter what you "call" it in your code.
Upvotes: 1