Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt Reg. Casting Object References

 
Ravi Pinnaboyina
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi frenz,

I had a doubt regarding Casting Objects to one another I understood about implicit casting, But when it comes to explicit conversions when does it throw Compile time Error and when does it give Runtime Exception(Classcast Exception).
 
Javier Sanchez Cerrillo
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you know the first thing that could happen is a compiler error and then the runtime error.

(Remember this 2 points

1.- If the object you are trying to cast is not from the same hierarchy of the class to promote it leads to compiler error.

2.- Once it compiles, If the object you are trying to cast is in the hierarchy but does not apply for an "is a" relationship it leads to java.lang.ClassCastException.


To clarify this:

Imagine you have 3 classes.

Animal (An abstract animal, maybe it has 8 legs or 4 who knows)

Dog (An specific animal, it has 4 legs for sure)

Cat (An specific animal, it has 4 legs too)

And the declarations of classes are:

class Dog extends Animal{}
class Cat extends Animal{}


Lets point out what you can do and what you can't do (---- means independent):

You can:
--------------------
Dog d = new Dog();
--------------------
Cat c = new Cat();
--------------------
Animal a = new Dog();
--------------------

Easy, isn't it?

You can't:
---------------------
Dog d = new Dog();
Cat c = new Cat();

c = (Cat)d; // Compiler error!!!. Explanation: (see number 1)
----------------------

Animal a = new Animal();
Cat c = new Cat();

c = (Cat)a; // ClassCastException!!!. Explanation (see number 2)
 
Ravi Pinnaboyina
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this same even in case of Interfaces.... Does we get a class cast Exception when using Interfaces?

Does the same rules apply to casting objects to interfaces?
[ February 19, 2007: Message edited by: Ravi Pinnaboyina ]
 
Javier Sanchez Cerrillo
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes its the same.

Almost all in Java is the same between classes and interfaces (in that sense (is a relationship)), except for the "instanceof" operator in which you can use any interface after "instanceof" and you won't get compiler time error. But if you use a class that is not part of the hierarchy you get compiler error.
 
Ravi Pinnaboyina
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Javier Now Iam clear with this.
 
Priya Viswam
Ranch Hand
Posts: 81
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic