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


class Dog{  
  int age;
	public Dog(int dogsAge) {    
    age = dogsAge;    
  public void bark() {    

  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);
    int spikeAge = spike.getAge();

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


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


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.

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?


Ok I think I understand now. Thanks.


You are creating new Object with initialized value = 7.