I have watched some programming tutorials and the guy in the tutorial said that you shouldn't use public variables and you should always use private variables.
Why should you use private variables instead of public variables?
Printable View
I have watched some programming tutorials and the guy in the tutorial said that you shouldn't use public variables and you should always use private variables.
Why should you use private variables instead of public variables?
Surely there are answers to this question on google, or even on this forum? What happened when you did a search? Why do you think you should use private variables?
The gist is this: public variables defeat several principles of object-oriented design, including encapsulation and detail-hiding, plus it opens your code up to malicious (or stupid) code making unwanted changes to your variables.
Nobody wants his/her private parts touched or modified without their explicit permission.
kind regards,
Jos
public variables can be altered by other classes in your program. Keeping your variables private shuts up shop basically but you still need to watch for privacy leaks in your code.
Is this right by the way lol? I'm still learning this stuff....
Best Regards
That's a pretty good description.
As Jos says, you don't want someone fiddling with your attributes without you knowing about it.
Your point about privacy leaks is also good. Date is a common example on this:
'myDate' is nicely encapsulated there. Whenever it is changed we validate it (for whatever reason), possibly changing some other data in this object to reflect the Date (say for weekends).Code:public class ExposedDate {
private Date myDate;
public Date getMyDate() {
return myDate;
}
public void setMyDate(Date myDate) {
//Do some validation stuff here
if (validateMyDate(myDate)) {
this.myDate = myDate;
}
}
}
However, our getter hands over a reference to that Date object. Since java.util.Date is not immutable (ie it has setters and can therefore be changed) someone can now get myDate and change it without it being validated.
nice one Tolls - cheers ;)