Constructor object


#1

class Dog{

int age;

public Dog(int dogsAge){
age = dogsAge;
}
public void bark (){
System.out.println(“Woof!”);
}

public static void main(String[] args) {
Dog spike = new Dog(18);
spike.bark();
}

}

In this code, why did we assign the bark method to the spike object?
the spike object is related to the dog age constructor. how did we print the bark method using the spike constructor object?


#2

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().

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 spike.

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 Dogs

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.