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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With