It's because of this line:
age = age + 1; //it's overwriting age parameter and not accessing age instance variable
If it was like that it would modify the age
instance variable
this.age = age + 1;
Pregunta
I have questions regarding encapsulation rules and difference between next two classes
class Phone {
public String model;
double weight;
public void setWeight(double w){
weight = w;
}
public double getWeight(){
return weight;
}
}
class Home {
public static void main(String[] args) {
Phone ph = new Phone();
ph.setWeight(12.23);
System.out.println(ph.getWeight());
}
}
In the book for Java for I OCA certification this is example of well encapsulated class and from set and get method we can access weight variable and pritns 12.23.
but what confused me is next class:
class Employee {
int age;
void modifyVal(int age) { // even if parameter is d instead age prints the same
age = age + 1; // even if parameter is d instead age prints the same
System.out.println(age);
}
}
class Office {
public static void main(String args[]) {
Employee e = new Employee();
System.out.println(e.age);
e.modifyVal(e.age);
System.out.println(e.age);
}
}
It print: 010
meaning that method modifyVal cannot access age variable. Can somebody explain why variable havent change after applying the modufyVal method and what is the difference?
Solución 2
It's because of this line:
age = age + 1; //it's overwriting age parameter and not accessing age instance variable
If it was like that it would modify the age
instance variable
this.age = age + 1;
Otros consejos
Inside the modifyVal
method, the operations on age
are scoped to the age
argument of the method, never to this.age
of the class instance.
Therefore this.age
is not incremented.
age = age + 1;
must be
this.age = age + 1;
When the instance variable and the method variable have the same name you have to tell java which one you are manipulating. In absence of this
it will take the method variable hence you should use this.age
.
void modifyVal(int age) {
age = age + 1; // not modifying age field of Employee class. local age field being passed to the function is being changed.
System.out.println(age);
}
System.out.println(e.age); // 0 : default value
e.modifyVal(e.age); // 1 : as age = age + 1; i.e, 0+1
System.out.println(e.age); // 0 : default value