![]() You have to operate on the assumption that, at some point, someone else will use your code - and that someone else could be you, a year down the line. Earlier versions didn't allow that, but as experience with Java accrues, the realization is finally dawning that public fields are OK. The modern Java APIs, like Hibernate, acknowledge this fact by accepting naked public fields on an equal footing with JavaBean-style properties. Basically, if you diverge in any way from the exact equivalent of public fields, you lose. In the world of JavaBeans, any such behavior will soon get in the way of the universal assumption that setters set, and getters get. Let me report on another fact from practice: no setter ever validates its input no getter ever calculates its result. And GridBagConstraints is a Java Bean in the purest sense: it's all about properties, no business logic there. Why? Because there's a case where this is in fact more practical. For example, take Java's own class GridBagConstraints- it has no methods at all (if you don't count clone, which it has anyway all Java classes inherit it from Object). People will give you a million regurgitated reasons why it is better, but it is only better in some cases, not in all of them unequivocally. Why is it that this is preferred and what no doubt silly thing am I missing/overlooking? But even though by hiding the variables they can't directly access them, the user can indirectly access and modify them which produces the exact same outcome. ![]() In the former method of doing things, the user could directly access the variables. However, I'm struggling to see why this is better. Now, in the main class, I would change the methods of setting name and telephone to the following: tName("Mary") Īccording to the lecture notes I'm following, this is more efficient (although could be made even more efficient by adding in a Person() method to allow for instantiation etc.) So now, I'll edit the Person class to declare the two Strings private and add get and set methods, like so: private String name Variables should be private inside a public class, as we don't want to allow people to see how this information is stored or to be able to edit information without authorisation. However, I know this is considered poor coding. If I did this, the test.print() would produce the output: mary 01234 567890 Then, in a main class, I could write the following code: class testPerson I could create it and define it as such: public class Person Say I have a Java class called Person, with a print method. Folks I'll start by apologising as I'm sure this has been answered elsewhere - I just can't find an answer that explains it in a way I understand! I'm doing an MSc conversion course and there are some elementary basics that I'm still struggling with this, including this one - why making a variable private is better.
0 Comments
Leave a Reply. |