<In what way does your code behave incorrectly? Include ALL error messages.>
My code behaves fine, I just don’t understand why some things are there and would like to know why they’re added.
Dog spike = new Dog(5);
Is the first Dog the Dog object, named Spike? What’s the = new for, does that specify it creating a new object and finally what is the last dog for? I know the (5); is for it’s age but what are the words for and what do they mean?
```
class Dog {
int age;
public Dog(int dogsAge) {
age = dogsAge;
}
public static void main(String[] args) {
Dog spike = new Dog(5);
}
}
<do not remove the three backticks above>
Dog spike = new Dog(5);
Once again is the first Dog the Dog object, named Spike? What's the = new for, does that specify it creating a new object and finally what is the last dog for? I know the (5); is for it's age but what are the words for and what do they mean?
This line is a lot like declaring a normal variable, for example:
int myNumber = 5;
^ ^ ^
| | |
type | |
name value
First we define of what type the variable must be, in this case an int (a number).
Then we give the variable a name, which we can use to call it later on, in this case: myNumber.
Then we store something inside the variable, because this is an int we store the number value 5 in it (That’s what the ‘=’ sign is for).
Now let’s look at this line again:
Dog spike = new Dog(5);
^ ^ ^ ^
| | | |
type | | |
name | |
keyword |
Object
You can see it is roughly build the same as the declaration of a normal variable.
First we define the type of the variable, Dog, because we want to store a Dog object in the variable.
Then we give the variable a name with which we can call it later on, spike in this case . Note that this is the name of the variable, and not the name of the dog!
Now it differs a bit from the normal declaration. We create a new Dog object, for that we use the use the ‘new’ keyword followed by the filled in constructor of the Dog class ( Dog(5) ).
The ‘=’ sign is used to assing the newly created Dog to the variable.
Actually, re-reading the lessons may have changed my mind.
Dog spike = new Dog(5);
The first dog comes from the Class Dog at the start of the code?
The spike is the name of it.
The new is a keyword.
Then the second dog is the class constructor?
Pretty close.
In Java variables must be of a specific type, like int, String and more. So a variable that will store a Dog object must be of the type Dog.
That is what the first Dog is for, now the compiler knows that what will be stored in that variable must be an object of the type Dog.
The second Dog is for creating the Dog-object itself.
To clarify your question about the name: spike is not the name of the dog, but the name of the variable.