ProAnswers.org

How to use this keyword in java?

The following example shows how to use this to reference instance variable.

 

 

class Person{

    private String name;

 

 

    public Person(String name) {

        this.name = name;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

public class Main{

    public static void main(String[] args) {

        Person person = new Person("Java");

        System.out.println(person.getName());

        person.setName("new name");

        System.out.println(person.getName());

    }

}