Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Typecasting

 
shruti patel
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why cannot we typecast the super class object to sublass?

final A a= new A();
is this legal?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

Yes. Though this example doesn't seem to be related to your question.
 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Pie
    Posts: 20608
    63
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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 ]
     
    Rahul Shilpakar
    Ranch Hand
    Posts: 132
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic