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.
The object that is created is a type
Beta, because that’s how it was created bynew. So, whenfoo()is called, it’s working on aBetaobject no matter what you “call” it in your code.