public static class Person {
public int age = 20;
public void adjustAge(int age) {
this.age = age + 20;
System.out.println("The age in adjustAge() is " + age);
}
}
I am just confused, can someone kindly advise me why we should have this.age instead of keeping it just as age?
I thought static variables can be called anywhere in a program because they belong to the class, but if a variable is non-static, then we need to use this.
I thought the variable age is a static variable as it was created with the class.
Can someone please clarify the reason why we use this.age as well as whether age variable a statis or non-static? Thanks in advance.Can be a static variable age called in a non-static method?
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Ramen
14 December 2020, 00:08
age is not static since the static property does not appear on the same line as the variable declaration
0
Guadalupe Gagnon
7 December 2020, 16:46solution
age on line 2 is not static, as it would need to say static on that line for it to be static. That means that age is an object variable that is unique to each object of the class that is created.
Now the keyword 'this' is needed on line 5 because the method has a variable named 'age' and the class has a variable 'age'. The default for the computer is to use the most local variable, which is the age declared as a method parameter on line 4. You are going to need to use the keyword 'this' to tell the compiler that you want to use the object's 'age' (from line 2) instead of the local 'age' (from line 4).
If the 'age' on line 2 was declared as a static variable that would mean that it was a class variable and not an object variable. Your understanding on that is correct, in that it would be the same for all objects of the class. In this case the proper way to refer to the class variable would be [ClassName].[VariableName]. So on line 5 it would be:
However, with static variables, you can also use the keyword 'this' inside the class to refer to the variable with no ill effects. This means that the code you shared would compile if the age at line 2 was static with the rest being the same. +10
Ahu
7 December 2020, 17:14
Thanks a million, now it is very clear.
+1