Reputation: 63
here i have some doubts about why we can use setter to change a private member but can't use "=" to change it. for example
public class Student {
private Date date;
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
public class HelloTest {
public static void main(String[] args) {
Student student = new Student();
student.getDate().setTime(1000);
//student.getAge()=100; not allowed
}
}
I don't know why I can use '.setTime(1000)' to change Date, but can't use '=100' to change age. In my mind, both getDate and getAge get the object reference. Thanks.
Upvotes: 3
Views: 92
Reputation: 1265
The left-hand side of an assignment must be a variable, not an object.
In my mind, both getDate and getAge get the object reference.
Yes, they do. Not a reference to the variable.
To make it clear, you'd better consider that they return an anonymous variable refering to the object.
At first, let's assume the field variable age
refers to an object. (It's null at the OP's example, but the same story can be applied.)
When you call getAge()
, it returns an anonymous variable that refers to the object.
The assignment operator means "let the left-hand side variable refer to the object that the right-hand side expression refers to". So if your student.getAge()=100
were allowed, it would result in the following situation.
Of course this is meaningless, so Java doesn't allow that at compile-time.
On the other hand, your first example .setTime(1000)
is not an assignment, so it works fine.
Upvotes: 0
Reputation: 495
You can't use =
because your getAge
method is returning a reference to an object. References, just like literals and other values, can be assigned to variables of the proper type. Your code doesn't work because it's like trying to write 10 = 100;
which makes no sense.
Upvotes: 0
Reputation: 44834
In the first example you are returning an Object then calling a method on that Object to change its value (not a new Object)
In the second example you are returning an immutable
object and then trying to autobox to change its Object
Upvotes: 1
Reputation: 2098
Any set...
or get...
method is a function inside the class, such as setAge
, getDate
, and setDate
in your example. In order to directly change a class variable from outside the class, you need to make it public
. There are reasons to not do this, and use setters/getters, but in some instances it's ok.
Upvotes: 0