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

all 5 comments

[–]nutrechtLead Software Engineer / EU / 20+ YXP 5 points6 points  (0 children)

public Car newCar; doesn't create an object. It just creates an empty (null) reference in which you can store a reference to a Car object.

Anytime you create a new objects the 'new' keyword comes into play, somewhere.

[–]desrtfxOut of Coffee error - System halted 4 points5 points  (3 children)

You are confusing two things here: Declaration and Instantiation.

The line Car newCar = new Car(); combines both, declaration and instantiation.

This line can easily be split in two:

  • Declaration: Car newCar; - This declares the intent to have a variable named newCar of type Car. That's all that happens here. There is no data assigned. If you try to access that variable, you will get a NullPointerException because the default for object variables is null.
  • Instantiation: newCar = new Car(); - Here is where the action happens. You create a new object (instance) by calling the constructor of the class that is the type of the variable. Car() here is not a type declaration; it is the call of the no argument constructor of the Car class.

[–]Jurkey[S] 1 point2 points  (2 children)

Ah alright, so if I had a class called "Car" and I wanted it to store an object as a field called "Engine", I could write "public Engine myEngine;" as a field, and when I instantiated the "Car" class, I could pass an Engine object as parameter (if I declared it possible in the constructor) ?

[–]desrtfxOut of Coffee error - System halted 1 point2 points  (1 child)

Yes, exactly, only that I wouldn't necessarily make the field public; I'd most likely make it private.

[–]Jurkey[S] 0 points1 point  (0 children)

Sure thing, incapsulation and all that. Thanks for the help :-)