Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Upcasting and Downcasting Doubt

807607Nov 24 2006 — edited Nov 24 2006
Which statement, when inserted at the indicated position in the following code, will cause a runtime exception?

class A {}

class B extends A {}

class C extends A {}

public class Q3ae4 {
    public static void main(String[] args) {
        A x = new A();
        B y = new B();
        C z = new C();

        // Insert statement here

    }
}

Select the one correct answer.

x = y;

z = x;

y = (B) x;

z = (C) y;

y = (A) y;
Soln
(c)

Statement (a) will work just fine, and (b), (d), and (e) will cause compilation errors. Statements (b) and (e) will cause compilation errors since they attempt to assign an incompatible type to the reference. Statement (d) will cause compilation errors since a cast from B to C is invalid. Being an instance of B excludes the possibility of being an instance of C. Statement (c) will compile, but will throw a runtime exception since the object that is cast to B is not an instance of B.

------------------------------------------------------------------------------------------------------

I never understand upcasting and downcasting concepts. Man this is weird. Is there any general tutorial that can help me with it...

Regards,
http://www.beginner-java-tutorial.com
Hemanth
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 22 2006
Added on Nov 24 2006
3 comments
368 views