Let me first say that whether it is a class
or struct
matters heavily in how this all works out, but for now I will ignore struct
to simplify things:
Now imagine in some other file, you do
Car truck;
This creates a variable (or field in some cases) that could contain a Car
instance, however it does not create such an instance. Note that if it is actually a field (because it is in a class
definition and not in a method) then it will get the default value null
. If it is a local variable then attempting to access it is a compiler error.
This isn't an instance of Car
and attempting to treat it as such will cause an error to occur unless it is a field and you are calling a method that will accept a null.
How is that different from
Car truck = new car();
By putting the = new Car();
before the ;
you are telling the language to give you an instance using the default constructor (that is a term for the ()
constructor). This causes a new instance of the class to be created and the constructor you provided to be called to initialize that new instance.
Note that in this case you have a valid Car
that will work as you expect, compared to the previous one where you did not have one at all.
In short if you want a place to hold a Car
use the first definition, if you actually want a car, use the second.
Now I am going to expand on struct
, it is important to keep in mind but they aren't nearly as common as classes so you can focus on the above.
Now imagine in some other file, you do
StructCar truck;
How is that different from
StructCar truck = new StructCar();
These are now identical, they both create a variable or field and calls the default constructor for the StructCar
. This will in turn set each field to its default value (calling the default constructor on any struct
and setting any class
to null
). This is a perfectly valid StructCar
but be careful, because every time you give it to someone (by saying calling a method and passing it as an argument) they will get a copy, not the original. Also note that in the definition of StructCar
you cannot define a default constructor, it will also do what I am describing here.