permaculture playing cards*
The moose likes Java in General and the fly likes Casting question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Casting question" Watch "Casting question" New topic
Author

Casting question

Sani babangida
Greenhorn

Joined: Jan 31, 2007
Posts: 16
I have two classes that are identical . they both extend a class A

b ---extends -->A
c ---extends--->A

is it possible to cast from b to c
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

No, it's not possible. In C++, you can get away with this by using an "old-style" cast; but in Java, all casts are checked at runtime, and this check would always fail.


[Jess in Action][AskingGoodQuestions]
Anton Uwe
Ranch Hand

Joined: Jan 10, 2007
Posts: 122
You would need to do a double casting like "C c= (C)(A)b;". The compiler would be happy then, but at runtime...
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Let's change the names of your classes a bit, then it will become more clear why this doesn't work.

Dog --- extends --> Animal
Cat --- extends --> Animal

If you have a Dog, can you cast it to a Cat - in other words, if you have a Dog, can you pretend that it's a Cat? No, you can't, because a Dog simply isn't a Cat.

(Remember that inheritance means "is a"; a Dog is an Animal, and a Cat is an Animal).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting question
 
Similar Threads
Generics question from Exam Lab
Dan's exam doubt
Multiple Interface Inheritance / Interface Inheritance
Implementing an interface - Is it IS-A ?
interview question