Вопрос

I am just starting to use greenfoot and I am looking into some examples and find that people often use "this", what does it exactly mean, I don't really understand, for example:

//set the animal's age
public void setAge(int age)
{
   this.age = age;
}
Это было полезно?

Решение

The this refers to the current instance of an object. So, in your example:

public void setAge(int age)
{
   this.age = age;
}

The use of this in the setAge setter means we are referring to the instance variable age in the this.age and setting that equal to the value of the parameter age. This means this.age and age refer to different variables.

Другие советы

The keyword

this

refers to an instance of the enclosing class. In your example, "this" will refer to the class containing that keyword.

You question might already have been answered here:

What is the meaning of "this" in Java?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top