given the following code, I have a question:
class A{}
class B extends A {}
class C extends B{}
public class Test {
public static void main(String[] args) {
You are trying to cast a super class reference variable to a sub class type. You cannot do this. Think practical, a super class object cannot contain independent methods (other than the super class' methods) of the sub class.
At run-time you might call a method in the sub class which is certainly not in the super class object.
class A{
public void foo(){}
}
class B extends A {
public void bar(){}
}
Now,
A a=new A();
B b=(B)a;
b.bar();
When you call like this the compiler, will only check whether the method bar() existed in the class B. That's it. It doesn't care about what is in the 'object' because it is created at runtime.
But at runtime, as said before there is no bar() method in the object a. b is just a reference that is pointing to object a but a contains only foo() not bar()
Hope you understood. Thank you.