A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Win a copy of
video training course this week in the
Java in General
Joined: Jan 31, 2007
Feb 15, 2007 10:34:00
I have two classes that are identical . they both extend a class A
b ---extends -->A
is it possible to cast from b to c
author and iconoclast
Joined: Jul 08, 2003
Feb 15, 2007 10:48:00
No, it's not possible. In C++, you can get away with this by using an "old-style" cast; but in
, all casts are checked at runtime, and this check would always fail.
[Jess in Action]
Joined: Jan 10, 2007
Feb 15, 2007 11:11:00
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
Joined: Aug 16, 2005
Feb 16, 2007 01:26:00
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
Animal, and a Cat
Java Beginners FAQ
JavaRanch SCJP FAQ
The Java Tutorial
Java SE 8 API documentation
I agree. Here's the link:
subject: Casting question
Implementing an interface - Is it IS-A ?
Generics question from Exam Lab
Multiple Interface Inheritance / Interface Inheritance
Dan's exam doubt
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2015