public properties directly?
This is well explained in tutorials. The whole reason why we have private fields and make them accessible via setters and getters.
I hope you get what I mean. I kinda lack the words to explaij it in shortened form.
Public *fields*. They are called "public fields". This distinction in terminology is important. Properties is a different concept, they are not fields. And getters/setters is not a pattern. It's an OOP concept. There is tons of info about it on the internet. This is a fundamental mechanism and very well explained. Try searching something like "why to use setters and getters". Here's how I explain it to people. In OOP, actually there's no concept of "public fields". There are "properties". They describe ... properties of the object)) I mean in non-technical sense - qualities of the object. And fields are nothing but one of the mechanisms to implement properties. You can implement properties without using fields at all, or you can implement one property using multiple fields. I.e. there is no restriction how exactly you implement properties. Properties are accessed with accessor methods - getters and setters. It just happens that in majority of cases properties are implemented with a single backing field of the same type. That's the reason, why in java this field should be private - because it's an IMPLEMENTATION DETAILS of the property. So, all this hassle with fields vs getters/setters is nothing but a result of java's stupid initial design for properties. There are languages much better designed with regards to properties. For example, in dart there are no fields at all, only properties. This is a well-designed OOP. Here's a sample class Something { String rwProp; final String roProp; String get evaluatedRoProp { return "calculated string value"; } set writeOnlyProp(String newVal) { thow Exception("not implemented"); } String get anotherRwProp() { ... } set anotherRwProp(String newVal) { ... } void usage() { var obj = new Something("ro prop value"); obj.rwProp = "new str value"; var roProp = obj.roProp; roProp = obj.evaluatedRoProp; obj.writeOnlyProp = "yet another"; obj.anotherRwProp = "again another"; var rwVal = obj.anotherRwProp; } If after searching on the internet you are not sure why to use getters/setters in java instead of simple public fields, then my recommendation - just use public fields. If you are asking this question, then you simply have no experience yet, and you're asking a question about something you never tried. Just try it. You'll run into problems yourself, not just read about it from other people, and will understand better why getters/setters are important.
Обсуждают сегодня