Reputation: 53
I have a question to keyword this and variables scope in methods. In general I know how to use this keyword, but got confused when observed the same result for all 3 options below into method balance. The question is, what is the correct implementation of option and why it treats all the options with the same result. Does it mean that if there is no local variable in the method balance, this keyword is ignored?
Thanks a lot!
option#1
public int balance(int balance) {
this.age = this.age + balance;
return age;
}
option#2
public int balance(int balance) {
age = age + balance;
return age;
}
option#3
public int balance(int balance) {
age = age + balance;
return this.age;
}
Code
package com;
public class Elephant {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public int balance(int balance) {
age = age + balance;
return age;
}
public int getAge() {
return age;
}
public Elephant(String name, int age) {
this.name = name;
if (age > 0) {
this.age = age;
}
}
}
package com;
import java.util.Scanner;
public class MainClass {
public static void main(String arg[]) {
Elephant e1 = new Elephant("Elephant1: ", 7);
System.out.printf("Elephant name: %s age: %s \n", e1.getName(), e1.getAge());
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
e1.balance(i);
System.out.printf("Entered deposit for e1: %d \n", i);
System.out.printf("Balance for e1: %s", e1.getAge());
}
}
Result for all 3 options is the same: Elephant name: Elephant1: age: 7 11 Entered deposit for e1: 11 Balance for e1: 18
Upvotes: 0
Views: 88
Reputation: 726489
Apart from situations when you need to pass or store a reference to the object from inside its instance method, you need keyword this
when resolving an unqualified name requires applying disambiguation rules.
For example, this code needs it:
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
Identifier age
could refer to the member field age
or the parameter age
. The compiler applies the rule that parameters and local variables "shadow" fields with identical names to remove ambiguity. That is why you must prefix age
with this
in the assignment; otherwise, the field wouldn't be assigned.
Your balance
method, on the other hand, does not need keyword this
at all, because it has no ambiguous name resolutions.
Upvotes: 4
Reputation: 1562
In Java, this
is always a reference to the current object. Object properties and methods of the current object can be accessed without explicitly mentioning this
. Which one you want to use (with or without mentioning this
), is often merely a matter of clarity and coding style guides.
Also see:
this
keyword in Java?Upvotes: 2