Why does "int dogsAge" equal the number in: "Dog spike = new Dog(7);"?


#1

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

  public void run(int feet) {    
    System.out.println("Your dog ran " + feet + " feet!");
    
  }
  
  public int getAge() { 
    return age;
  }

	public static void main(String[] args) {   
    Dog spike = new Dog(7);
    spike.bark();
    spike.run(20);
    int spikeAge = spike.getAge();
    System.out.println(spikeAge);
	}
}

I was running through the code trying to figure out why everything works, but at the end the dogs age equals 7. Why? it doesn't look like "int dogsAge" is even defined..


#2

You forwarded the dogsAge 7 at that line: "Dog spike = new Dog(7);"


#3

What specifically did that? The "new Dog(7);"?

I'm assuming the new parameter in "new Dog" overwrites the original Dog class parameter?

Thanks for replying btw.


#4
new Dog(7);

This calls your constructor function of Dog:

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

where you said that the parameter should be stored in the age variable. Now for this instance of Dog age is 7 because that is the value you assigned to it via the call of the constructor method. Is this clear?


#5

Ok I think I understand now. Thanks.


#6

You are creating new Object with initialized value = 7.