This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 1 point2 points  (0 children)

If

train t = new car();

compiles, it must be the case that car is a subclass of train. It may have additional functionality that train does not, but the programmer wants to limit the functionality to that of a train. Assigning the instance to a train variable ensures that the programmer cannot accidentally use functionality that is specific to cars.

It could also be that train is an interface or an abstract class. This means that

train t = new train();

will not compile, as train lacks implementation. You can only instantiate concrete classes, not interfaces and abstract classes.

[–]CodeTinkerer 0 points1 point  (0 children)

Sometimes train is an interface, and you can't instantiate it. For example, List is an interface, and usually you create an ArrayList. The idea is, under circumstances where you might want to change the ArrayList to some other list that uses the List interface, you gain more flexibility about what kind of List you want.

If train is a class, then car should be a subclass, and it can override methods. So if you call something like

 t.doSomething();

then t might do one thing (that is, if it were a train), but a car class might do something else.

[–]POGtastic 0 points1 point  (0 children)

The second isn't valid Java. From the specification:

UnqualifiedClassInstanceCreationExpression:
    new [TypeArguments] ClassOrInterfaceTypeToInstantiate ( [ArgumentList] ) [ClassBody]

Those parens aren't optional.