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