java this keyword

前端 未结 7 1431
野的像风
野的像风 2020-12-11 09:00

I have read that in Java you don\'t have to explicitly bind the this keyword to object, it is done by interpreter. It is opposite to Javascript where you

相关标签:
7条回答
  • 2020-12-11 09:54

    In java 'this' is a keyword, basically used to refer to the current object. In the following example the setter methods are using 'this' to set the values of name and age of current object.

    public class Person {
    
      String name;
      int age;
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      public int getAge() {
        return age;
      }
    
      public void setAge(int age) {
        this.age = age;
      }
    
      public static void main(String[] args) {
        Person p = new Person();
        p.setName("Rishi");
        p.setAge(23);
        System.out.println(p.getName() + " is " + p.getAge() + " years old");
      }
    }
    
    0 讨论(0)
提交回复
热议问题