I have 3 classes A,B and c as follows
A.java
class A
{
protected A(){
System.out.println("A");
}
void show()
{
System.out.println("showA");
}
}
B.java
class B extends A
{
B(){
System.out.println("B");
}
void show()
{
System.out.println("showB");
}
}
C.java
class C extends B
{
C(){
System.out.println("C");
}
void show()
{
System.out.println("showC");
}
public static void main(String... args)
{
A a= (B)new C();
a.show();
}
}
When executed gives the output
D:\java\rmi\Hello>javac C.java
D:\java\rmi\Hello>java C
A
B
C
showC
I know a superclass cannot be casted to a subclass.But in the output why is it executing the C class method (show) when there is a cast to the super class B?
A a= (B)new C();
And if this is right then what is it that is getting casted to B?
I mean here new C() would call the C constructor and hence the respective outputs but
what is the difference between new C().show(); and (B)new C().show(); what is getting casted here?
Class B does not extend C, so it has no knowledge of it and connot be casted to C. With java, you can down cast but not upcast.
OK:
-> C inherits from B, so cast is possible
Not OK
-> B does not inherit from C, so it cannot be cast to it
see also: Downcasting in Java
Edit:
Please consider to edit your question, as most users tend to correct an error first. (Remove the error and break it down to your original question)
“what is the difference between new C().show(); and (B)new C().show();”
This is called ‘polymorphism’. there is no difference between the two calls, as java will always execute the method of the lowest level of the hierarchy.
For example:
This would output: