tags:

views:

155

answers:

3
Dollar dollar= (Dollar) object;

What does this snippet in do? Is it even Java? Or Smalltalk? I found it in TDD, which i think was written with Smalltalk in mind.

+9  A: 

This could be Java. It basically casts an object of generic type (perhaps just Object) to a Dollar object.

Example:

Object object = ObjectFactory.getObject(); // Gets object
Dollar dollar = (Dollar) object; // Cast to Dollar object, will throw an exception
                                 // if this isn't possible
dollar.dollarMethod();   // I can now call Dollar methods
kgiannakakis
+4  A: 

It creates a new variable of class Dollar, with the name dollar. Then it assigns a value to that variable by casting to Dollar a variable named object. It's valid Java code, providing there's a class named Dollar defined. But if the variable named object is not of class Dollar it might throw a ClassCastException.

Andrei Fierbinteanu
It is not the **variable** that must be of class Dollar; the **instance** stored in that variable must be an instance of Dollar (or of a subclass of Dollar)
Carlos Heuberger
A: 

this actually casts the generic type (Object) to Dollar type.

Saher