CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: UpCasting

  1. #1
    Join Date
    Jun 1999
    Location
    Israel
    Posts
    42

    UpCasting

    Hey all,

    Here is a problem:
    I have tree classes, A and B, also known that B extends A.

    now...

    A a = new A();
    B b = (B)a;




    The code above throws a ClassCastException, why ?

    I've been working for couple of years with C++ and I'm pretty sure this kind of casting is possible, why not in Java ?

    If I'm right, and this kind of casting cannot be done, what's the big idea behind OOP in Java ?


    Thanks,
    Ronen.


  2. #2
    Join Date
    Nov 1999
    Location
    Germany
    Posts
    42

    Re: UpCasting

    Hi,

    it doesnt work. If you say B extends A


    class B extends A




    so I think you only can :


    B b = new b();
    A a = (A) b;




    Thats OOP! You cant cast A to B. Because A doesnt know anything from B.

    A child can behave like a parent, but a parent doesnt know anything about their childs.

    Martin


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured