1

I was attempting some practice exams for my Java final coming up and I came across this question.

Consider the following class definitions and indicate whether 'Test.main()' would compile successfully. If it does compile, indicate whether it would run successfully or if not, indicate what Exception would be thrown.

public class A {
    public int method(int[] a) {...}
}
public class B extends A {
    @Override
    public int method(int[] a) {...}
}
public class C extends B {
    @Override
    public int method(int[] a) {...}
    public void otherMethod() {...}
}
public class Test {
    public static void main(String[] args) {
        A a = new C();
        B b = new B();
        b = (B) a;
    }
}

I thought that Test.main() would compile but throw a runtime exception due to the fact that a is of actual type C and we are trying to cast it to type B. This is not the case as the answers say this is fine.

I'm pretty confused about the rules of casting where there is a hierarchy deeper than 2 levels involved. The lecture slides don't really have this kind of information!

So what are some hardfast "rules" to keep in mind if this type of question pops up on the exam?

4

2 に答える 2