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
}