-1

I am learning java and encounter a doubt. Like in python to access class variable we use self but in java, the same thing is done but without this or self.

class Dog {
 int size;
 String name;
 void bark() {
     if (size > 60) {
         System.out.println(“Wooof! Wooof!”);
 } else if (size > 14) {
     System.out.println(“Ruff! Ruff!”);
 } else {
     System.out.println(“Yip! Yip!”);
  }
 }
}

class DogTestDrive {
 public static void main (String[] args) {
 Dog one = new Dog();
 one.size = 70;
 Dog two = new Dog();
 two.size = 8;
 Dog three = new Dog();
 three.size = 35;
 one.bark();
 two.bark();
 three.bark();
 }
}

How three object access size variable without using this keyword.

Output:

Wooof! Wooof!
Yip! Yip!
Ruff! Ruff!
  • 2
    The `this` keyword is optional in Java, as discussed broadly in [this question's answers](https://stackoverflow.com/q/2411270/). – jirassimok Nov 10 '19 at 03:48

1 Answers1

1

this keyword is optional in java. In this example you can actullay use this keyword also. Only scenario that you will need to use it mandatary is when referring to a field which is named the same both locally and globally.

example:

class Test
{
  private int size; //global 

  public void method(int size)
  {
    this.size = size; //this.size refers to the declaration within the class, not the method local variable

  }
}
Sandeepa
  • 3,457
  • 5
  • 25
  • 41