Instantiating objects


#1

I have a few questions about instantiating objects (Exercise 7):

class Dog{

    int age;

    public Dog(int dogsAge){
    
        age = dogsAge;
    }


    public static void main(String[] args) {
        Dog myDog = new Dog(1);
    }
}
  1. In this example, the main function in which we instantiate the Dog class is within the dog class itself. Is there ever an issue instantiating the object within itself?

  2. When instantiating the dog class using:

Dog myDog = new Dog(1);

The Dog from Dog myDog is referencing the class, and the Dog from new Dog(1) is referencing the constructor.

Why does the constructor have to match the class name?

The below gives an error after changing the constructor name, even though in the line where we instantiated the class we also reflected the name change.

class Dog{

    int age;

    public Dog1(int dogsAge){
    
        age = dogsAge;
    }


    public static void main(String[] args) {
        Dog myDog = new Dog1(1);
    }
}

I apologize if these are stupid questions, I'm playing around with the code as I go and could not find a reason for this.


#2

1) No
2) Not necessarily, because that's not a variable. "Referencing" might not be the word to describe what happens there. You're also making a new "dog" so in the English sense at least, it is the class that refers to. If you write Dog.f then that also means the attribute f in the class. I don't know what really happens, I can only question your assumptions. Avoid assumptions unless you strongly keep in mind what they rely on to be true and you can verify them.

Your Dog1 is not a constructor, it's a method, you said yourself that a constructor has the same name as the class.


#3

@chriskoh
Read
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
very closely......