2

Given the Java class City.

What is the point of writing City springfield = new City();

Instead of springfield = new City();

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Álvaro Franz
  • 699
  • 9
  • 26
  • 9
    to make it compile? – Andrew Tobilko Aug 27 '19 at 10:07
  • 3
    to know what `springfield `is supposed to be? – jhamon Aug 27 '19 at 10:08
  • @jhamon If we assign the variable a new instance of a class City, why would it be something different than City? – Álvaro Franz Aug 27 '19 at 10:09
  • 3
    It can also be an interface City implements – Ori Marko Aug 27 '19 at 10:10
  • why would you assign a `City`and not an `int`in the first place? Because you said `springfield`is a `City` – jhamon Aug 27 '19 at 10:10
  • Suppose City extends 'Location', then is springfield a City, or a Location ? – jr593 Aug 27 '19 at 10:10
  • 2
    @AlvaroFranz yes, it could be `HumanSettlement springfield = new City();` where `City` is a subclass of `HumanSettlement` – Andrew Tobilko Aug 27 '19 at 10:11
  • @Arnaud I don't know yet what interface type is, because I just started learning, so I guess that will be the answer to my question. Thank you. – Álvaro Franz Aug 27 '19 at 10:12
  • Because you should specify the type of the Instance or a higher type or an interface that the class implements. – Mehdi Benmesssaoud Aug 27 '19 at 10:17
  • @AlvaroFranz `City springfield` is just a reference on the stack. To create an object you have to use `new ClassName()` where the `new` operator dynamically allocates the memory on the heap and then constructor is called. So basically you declare the reference of some type (`City` in this case) and then you create an object itself. That is why you have to repeat class name - 1)to create the reference and 2) to create the object – Andre Liberty Aug 27 '19 at 11:20

1 Answers1

4

There is no point, since Java 10, for local variables. For local variables you can instead write:

var springfield = new City();

Also, you can create an object without introducing an object reference, if you create an object in an expression. Typically this is done in a method call:

settlements.add(new City());

You must still repeat the class name for attributes (fields).

But, there is an exception to this. If you want to program to an interface, you must indicate the type of object you are constructing and the interface class you want the object reference to have:

Settlement springfield = new City();
Raedwald
  • 46,613
  • 43
  • 151
  • 237