DEV Community

Bharath kumar
Bharath kumar

Posted on

this

this keyword:
Within an instance method or a constructor, this is a reference to the "current object",
the object whose method or constructor is being called.
this refers to a reference of the current class.

class Monkey { 
   String name="Monkey";
  void getname1() {
    System.out.println("animal name : " + this.name);
  }
}
class Horse extends Monkey {
    String name= "Horse";
  void getname2() {
    System.out.println("animal name :" + this.name);
  }
}

public class Main {
  public static void main(String[] args) {
    Horse a = new Horse();
    a.getname1();
    a.getname2(); 
  }
}

Enter fullscreen mode Exit fullscreen mode

Output:

animal name : Monkey
animal name : Horse
Enter fullscreen mode Exit fullscreen mode

Reference:https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Top comments (0)