Java - Use this to implement getter and setter

Introduction

Here we can use this to reference instance variable in getter and setter

class Student {
  private int id; // An instance variable

  public void setId(int id) {
    this.id = id;
  }

  public int getId() {
    return this.id;
  }

}

You can use the Student as the following code.

Demo

class Student {
  private int id; // An instance variable

  public void setId(int id) {
    this.id = id;
  }//from  www.ja v a  2  s. c  o  m

  public int getId() {
    return this.id;
  }

}
public class Main {
  public static void main(String[] args) {
    Student s = new Student();
    s.setId(1);
    System.out.println(s.getId());
 }
}

Result

Related Topic