File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Typecasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Typecasting" Watch "Typecasting" New topic
Author

Typecasting

shruti patel
Ranch Hand

Joined: Mar 10, 2008
Posts: 52
why cannot we typecast the super class object to sublass?

final A a= new A();
is this legal?
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336


final A a= new A();
is this legal?

Yes. Though this example doesn't seem to be related to your question.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Susan Smith
Ranch Hand

Joined: Oct 13, 2007
Posts: 224
Shruti, I think there are two separate questions in your post, right?
I had same confusion with Paul also at the beginning.

For the 1st question:
>>>> why cannot we typecast the super class object to sublass?
Maybe this analogy will help:
Superclass --> Animal
Subclass --> Lion
Try the ".. IS A(N) ..." test:
  • Lion IS AN animal --> Yes
  • Animal IS A lion ?? This one doesn't make sense, right?


  • Hope it helps.
    [ July 17, 2008: Message edited by: Susan Smith ]
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19693
        
      20

    To come back to IS A(N), you will need to cast if you can't use IS A(N) but can use MIGHT BE A(N):

    Animal IS A Lion? No.
    But Animcal MIGHT BE A Lion? Sure.

    If this is also not the case you can never cast between the two:
    String IS AN Integer? No.
    String MIGH BE AN Integer? No.


    Please note that you should never cast unless you are really sure that the cast will succeed, for instance by checking with instanceof. Remember, if the cast is invalid it will throw a ClassCastException. This happens if the Animal MIGHT BE A Lion but is in fact a Tiger, and you still try to cast it to a Lion.
    [ July 17, 2008: Message edited by: Rob Prime ]

    SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
    How To Ask Questions How To Answer Questions
    Rahul Shilpakar
    Ranch Hand

    Joined: Aug 29, 2006
    Posts: 132
    Suppose any Superclass has 3 Characteristics like (1, 2, 3).
    So its obvious that Subclass should have all the three Characters of its Superclass in it. And it can also has its own characteristics (4,5)(it means subclass is more specific).

    Now, Subclass has total 5 characteristics (i.e. 1, 2, 3, 4, 5 ).

    Now want to cast Superclass in to Subclass means you want Superclass of (3charactoristics) exactly like Subclass of (5 characteristics ).

    How can characteristics 4 & 5 will come in Superclass?

    Am right! Thats the answer.


    Perform for today. Adapt for tomorrow.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Typecasting