Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upcasting when making object

Tags:

java

upcasting

Say you have a Shape base class and various derived types: Circle, etc.

Is there ever any reason to upcast right there when making a new object, by writing this:

Shape s = new Circle();

instead of this:

Circle s = new Circle();

and are the s objects made by each of these two statements in any way different from each other?

like image 550
Jean-François Corbett Avatar asked Mar 29 '11 08:03

Jean-François Corbett


2 Answers

Those two statements will produce the same object as far as the JVM is concerned. It's not uncommon to show that you only plan to use the object for the base class or interface. E.g. this is common:

List<String> list = new ArrayList<String>();

Although generally not a good idea, you can cast the Shape back into a Circle if you know for sure that it is one, e.g. with Shape s you can bring it back to a Circle c with:

if (s instanceof Circle) {
    Circle c = (Circle) s;
    // handle Circle case
}
like image 85
WhiteFang34 Avatar answered Oct 21 '22 04:10

WhiteFang34


You can argue that your first example (i.e. Shape s = new Circle();) can have the same advantages as "coding to the interface" even though Shape might be an abstract or even a concrete base class. So for example, if you only ever use the methods defined on Shape and not those specific to Circle, then you can quite easily just change the implementation you are using to a Square for example just by changing one line of code, i.e. Shape s = new Square();.

The objects are the same in both of your examples, the reason why the first option can be considered better is more of a style thing. Coding to interfaces can make a code base more easily extensible and modifiable.

like image 34
brent777 Avatar answered Oct 21 '22 04:10

brent777