Exercise on OOP


#1

hi All,fter writing the below code for exercise OOP, its giving me error. what am i doing wrong?

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


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

#2

Technically the code you have here will compile and work. Although by convention setting class variables in the constructor is done with the this key word.

this.age = dogsAge;

#3

Here below i have commented where you went wrong

// add a modifier public , private or protected
public class Dog {
    int age;
    public Dog(int dogsAge) {
        age =dogsAge;
    }


    public static void main(String[] args) {
        Dog spike = new Dog(3);
        
        //print statement to test
        System.out.println(spike.age);
    }
}// you forgot to end the class

Also check out the excerpt on the this keyword

// add a modifier public , private or protected
public class Dog {
    int age;
    public Dog(int age) {
        //usually the this keyword is used
        //when the arguments in the constructor is
        //exactly the same as the attributes of the class
        // so to distinguish between them the this keyword is used
        this.age =age;
        
        //but if you write age = age
        // he compiler will warn
    }


    public static void main(String[] args) {
        Dog spike = new Dog(3);
        
        //print statement to test
        System.out.println(spike.age);
    }// end main
}// end Dog class

#4

You're missing a curly bracket