The reason why the function
bark() is part of spike because spike is a
Dog object and the
Dog class has this function.
Think about it this way. Every dog is different. They can for example differ in age.
But all dogs bark.
This is why the age has to be set when creating a
new Dog(18) object and the
bark() method is already part of it.
This is not entirely correct. spike in this case is not related to the
Dog() it is a
Dog(). Because a
Dog object can bark() since it has the function. It means spike can bark since it is a
Dog spike = new Dog(18); With this line of code you create a
new Dog() with the age of 18. The name of the variable this
Dog() is stored in is called
We don’t. We create a new dog and store it in the variable spike. Since spike contains a
Dog object we get all the functions that are part of
Dog as well.
You could see the class Dog as a blueprint for spike. This blueprint can be used for other dogs as well. Try making another dog called david for example (
Dog david = new Dog(12);). You would see that david is different from spike if you inspect it more closely.
spike has an age of 18
david has an age of 12
But they both
bark() since they are both
It is important to understand this subject if you want to become better. It is used a lot when you start Object Orientated Programming (OOP). If it is not clear yet how this works i recommend asking more questions.
More information can be found here its a dry read but it might help making things clearer.