This question already has answers here:
Java Getters and Setters
(17 answers)
Closed 9 years ago.
My Java is a bit rusty (been doing C# for the last couple of years). Also I hope this won't be a very subjective question.
Anyway say I had class Person (yeah a bit of a cliche, I know), with no behaviour (C# version):
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
// say 10+ properties
}
How would the equivalent Java version look like ?
I know I can write bunch of getters and setters (but say I had 10+ properties), it feels like a lot of boilerplate.
Is it considered bad practice to just do:
public class Person {
public String name;
public int age;
// rest of the stuff here
}
I feel a bit uneasy about this. I realise there is no "right answer" but, I'm more interested in the general conventions and best practices.
You should write getters and setters. Or better - let your IDE generate them automatically. Otherwise you break the encapsulation. Also maybe you need just a getter.
Another advantage of using a getter or setter can be doing some checks or preprocessing before returning or setting the field.
Here is a sample code snippet:
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
Optionally you can use http://projectlombok.org/ and write it like this using annotations:
#Getter #Setter
private String name;
The code generation is done compile time.
It's better to have getter/setters to return the fields so that you can encapsulate the way the fields are calculated. Although it happens rarely, there may come a time when you want to change something like this:
getBalance()
{
return this.staticBalance;
}
to this:
getBalance()
{
return calculateBalance();
}
And the only way in Java to change field behavior without potentially changing tons of code (or worse requiring your API users to change bunches of code) is to use getters and setters.
Other benefits are:
Ability for subclasses to override the behavior
Improved thread safety because you can synchronize access
Writing the boilerplate is tedious, but a good IDE will just generate those methods for you from the field names.
You have to create manual functions to do it.
So first, you create a backing field.
private String _backingString
Then you create getters and mutators
public String getBackingString()
{
return this._backingString;
}
public String setBackingString(String value)
{
this._backingString = value;
}
It's the Java convention - there's no other way around it. However, you'll be pleased to know most IDEs have tools to generate these. Just google around for your favourite IDEs generator tool.
You can see this SO question on how to do this in Eclipse.
You should do getters and setters for each. Modern IDE's make it easy because they have auto-insert option.
Eventually you can create get and set methods in Calendar's class style.
I often use both approaches, having getters and setters and not. I always use private fields which force the use of getters and setters in my model. Using JPA and Hibernate my model is tied to my DB schema. Then for my DTOs which are normally used for things like RESTful services I use mostly public fields with no getters and setters. These DTOs have no logic and get marshaled out to JSON or created from JSON that's being set from a client so I find no need for the getters and setters. I usually don't end up override equals and hashCode for these too. They are as simple as possible.
So I don't think there's a right or wrong way and it depends on usage.
And if you are going to create you getters and setters let your IDE do the work for you.
Which IDE are you using? In Eclipse you can create them automatically from the source menu, and their names are derived from the field names.
Code:
private String myField;
public String getMyField()
{
return this.myField;
}
public void setMyField(String value)
{
//validation stuff
this.myField = value;
}
Related
Please read before referring me to post like those, I'm asking about a very specific case :
Why use getters and setters/accessors?
What is the use of encapsulation when I'm able to change the property values with setter methods?
Let's take for example a JAVA JEE application, those are basically websites.
Your bank website is probably a JAVA JEE application.
On those we are a generally a team of 10-15 devellopers, nobody except us uses our code, nobody imports our package and uses our objects.
The backend usually have DAOs to access the database and Value objects to transfert data to the presentation layer.
The VOs are perfect copies of the entities, example :
public class UserVo {
private String name;
private String email;
private String password;
public UserVo(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
So you get an entity, you convert it to a VO for "layer separation" (which I don't see the point either because if you change an entity you change the VO then you change the code in the presentation layer that use that VO but whatever)
First of all a VO is suposed to be immutable, but on all the projects that I've worked for they are mutable.
My question is : is there an advantage here to have getters/setters ?
There is no logic inside, some will tell you that a setter can do
some validation but this is not useful because all our code is
unit-tested so there is no need to validate anything in the
setters.
Since all properties have a get/set is is exactly the same as if they
were public.
When the implementation changes the getter/setter are changed too and
all the code that uses the old getter/setter is refactored/modified.
I often get told about data hiding, that the user won't be able to
access a private property : what? the user is browsing a website.
So, why is everybody so attached to those getter/setters? if I uses public properties instead of those getter / setters I will be ridiculed, everyone saying things like "don't you know about encapsulation", "you should NEVER have public fields"
My take on it is that it's useless, but everybody does it because it is how it has always been done and nobody ever ask questions about it.
Am I wrong?
Thanks.
Am I wrong? In the example you've shown I would state that no, you're not wrong. This has to do with the distinction of objects vs data structures and it seems that UserVo is a data structure thus rendering those getters and setters totally useless.
Objects hide their data behind abstractions and expose functions that
operate on that data (including getters and setters). Data structures expose their data and have no
meaningful functions. (Clean Code, Robert Martin)
Now in Java everything is an actual object and the language does not supports data structures. But that does not force me to create an object to act like a data structure.
I mean why on earth would I prefer this
public class Point {
private double x;
private double y;
public double getX(){
return x;
}
public double getY(){
return y;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
}
over this?
public class Point {
public double x;
public double y;
}
Java was designed without any idea of implementing a universal access principle (where the caller doesn’t distinguish whether they are using a field or a method, they’re called the same way). That means, rather than introduce a getter only once you need it, you tend to put it in up front because it will be a pain to introduce it later.
So people naturally default to using getters/setters. Also naturally, the reasons for doing this are fear-based and nebulous-sounding because it is all about dealing with an unknowable future.
One practical consideration is most pojos get used with frameworks or libraries that expect getters and setters. In those cases the choice is out of your hands.
In many cases validations and conversions are better off being done outside of the pojos (see validators in spring mvc for instance, or Jpa converters), but in other cases we need getters/setters for validating/converting (or are afraid we will eventually).
TLDR: the language was designed in a way that penalized putting in getters/setters only when needed, so you got a culture of people insisting on them upfront in all cases.
There are languages where immutability is widespread, like clojure. They get by fine without encapsulation. Immutability is still unfamiliar to a lot of java programmers and the best practices assume mutable state. To me the posted Value Object would be better off being immutable because when otherwise when reading the code I can't discount the possibility something will modify it after it is sent.
So, why is everybody so attached to those getter/setters? if I uses
public properties instead of those getter / setters I will be
ridiculed, everyone saying things like "don't you know about
encapsulation", "you should NEVER have public fields"
My take on it is that it's useless, but everybody does it because it
is how it has always been done and nobody ever ask questions about it.
Because it is a religion – meaning "Strictness of fidelity in conforming to any practice, as if it were an enjoined rule of conduct." – Webster
This question already has answers here:
Are getters and setters poor design? Contradictory advice seen [duplicate]
(16 answers)
Closed 9 years ago.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior. In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public? Or just treat the class as a data structure?
I don't think so. It depends of the lifetime of your Object and its "exposure" (external modification).
If you're only using it as a data structure, exposing fields in secure way (final) sounds enough:
public class Person {
public final String firstName;
public final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
The term POJO was intended to distinguish classes from JavaBeans or any other convention. As such a POJO is by definition NOT required to do anything.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior.
This is called encapsulation and a good principle.
In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public?
That is an alternative approach. Some projects may forbid this approach while others may encourage it. Personally, I would favour this approach for classes which are encapsulated in some way already e.g. they are package local.
There is a view that some day in some way your class might have additional requirements and changing the "API" will be impossible. This goes against the YAGNI principle and very rarely proves to be the case and when it does has a much lower cost than adding lots of methods which don't do anything.
However, this is not always the case and if you don't use accessor methods you should consider what the impact will be on the project if you have to change it later. Using accessor methods every where means you never need to worry about this.
In summary, if you are pretty sure accessor methods are pointless and it won't be a problem to add them later, I would say you should use your judgement. However if you are not sure if it could be a problem in the future or you don't want to have to worry about it, use accessor methods.
The definition of POJO doesn't mandate getter/setter.
Experimentally, I am not using getter and setter in my current project.
The approach I am taking is this one:
unless necessary, don't provide getter/setter.
So far, I didn't find a case where I really needed get/set.
Some friend told me: "having get/set is helpful if in the future you need xyz"; my reply has been: when -in the future- I need to do so, I will provide the getter and setter; I don't want to anticipate anything.
The objection about incapsulation, that some may raise, is not really a valid one: providing getter and setter breaks incapsulation in the same manner, plus you have additional lines of (useless) code. Bugs may also lay in getter and setters.
This is an example of one of a non-trivial domain class:
public class SSHKey implements IsSerializable {
public Long id;
public Long userId;
public String type;
public String bits;
public String fingerprint;
public String comment;
#SuppressWarnings("unused")
private SSHKey() { // required by gwt-rpc
}
public SSHKey(String text) throws InvalidSSHKeyException {
Ensure.that(text != null, new InvalidSSHKeyException("Invalid Key"));
text = text.trim();
String[] parts = text.split(" ", 3);
Ensure.that(parts.length >= 2,
new InvalidSSHKeyException("Invalid Key"));
type = getType(parts);
Ensure.that(type.equals("ssh-rsa") || type.equals("ssh-dss"),
new InvalidSSHKeyException(
"Key must start with 'ssh-rsa' or 'ssh-dss'"));
bits = getBits(parts);
comment = getComment(parts);
}
private String getBits(String[] parts) {
return parts[1];
}
private String getComment(String[] parts) {
if (parts.length == 3)
return parts[2];
return type + " " + bits.substring(0, min(15, bits.length())) + "...";
}
private String getType(String[] parts) {
return parts[0];
}
}
The constructor takes the responsibility to validate and prepare the data to be manageable. Thus this logic doesn't need to be in a setter/getter.
If I was shown object with public members some years ago, I would probably not like them; maybe I am doing something wrong now, but I am experimenting and so far it is ok.
Also, you need to consider if your class is designed to be extended or not (so, foresee the future is part of the requirements), and if you want your object to be immutable. Those things you can only do with get/set.
If your object must be immutable, and you can avoid the empty constructor, you can just add 'final' to the member instances, btw.
Unfortunately I had to add IsSerializable (similar to java.io.Serializable) and an empty constructor since this is required by gwt. So, you could tell me then "you see? you need the getter an setter"; well not so sure.
There are some jdbc frameworks which promote the use of public fields btw, like http://iciql.com
This doesn't imply that this project is correct, but that some people are thinking about it.
I suppose that the need of getter/setter is mostly cultural.
The issue with making the members accessible is that you no longer control them from inside the class.
Let's say that you make Car.speed accessible. Now, everywhere in you program there can be some reference to it. Now, if you want to make sure that speed is never set a negative value (or to make the change synchronized because you need to make it thread safe), you have to either:
in all the points where speed is accessible, rewrite the program to add the control. And hope that everybody that changes the program in the future remembers to do so.
make the member private again, create the getter and setter methods, and rewrite the program to use them.
Better get used to write getter and setter from the beginning. Nowadays, most IDEs do it automatically for you, anyway.
The canonical answer to this is: You don't know whether your simple data structure will stay so simple in the future. It might evolve more than you expect now. It might be also possible, that anytime soon you want some "value changed" observer in that bean. With getter and setter methods you can do this very simply later without changing you existing codebase.
Another pro point for getter/setter is: If in Rome, do like the Romans... Which means in this case: Many generic frameworks expect getter/setter. If you don't want to rule all these usefulls frameworks out right from the start then do you and your colleagues a favour and simply implement standard getter/and setters.
Only if you expose a class in a library that's used beyond your control.
If you do release such a library, the Uniform Access Principle dictates that you should use getters and setters in order to be able to change the underlying implementation later without requiring clients to change their code. Java doesn't give you other mechanisms to do this.
If you use this class in your own system, there's no need: your IDE can easily encapsulate a public field and update all its usages in one safe step. In this case, brevity wins, and you lose nothing for the time where you need encapsulation.
I think it's a good idea to use getters and setters, unless you have very specific speed/memory/efficiency requirements or very simple objects.
A good example is a Point, where it is probably both nicer and more efficient to expose it's .x and .y variables.
That said, it will actually not be a big effort to change the visibility of a few member variables and introduce getters and setters even for a large codebase, if you suddenly require some logic in a setter.
JavaBeans require getters and setters. POJOs do not, anyway this has its benefits
The objetive of the getters and setters is to achieve encapsulation, which manages the internal state of object. This allows you to add or change business rules in your application after the application has been implemented only change the getter or setter code, example, if you have a text field that only allows for more than 3 characters can check before assigning it to an attribute and throw an exception, other reason for not doing this is if it's possible you'll want to change the implementation or change variable names or something like. This cannot be enforced if the field is publicly accessible and modifyable
anyway you can use your IDE to generate setters and getters.
If you are developing a simple application can be recommended, if your application is complex and must give maintenance is not recommend.
for the data-type objects, like POJO / PODS / JavaBean, at python you have only public members
you can set those and get those easily, without generating boilerplate setter and getter code(in java these boilerplate code usually(98%) exposes the inner private tag as noted in the question)
and at python in the case you would need to interact with a getter, then you just define extra code only for that purpose
clean and effective at the language level
at java they chose the IDE development instead of changing base java, see JavaBean e.g. how old that is and java 1.0.2 is how old...
JDK 1.0 (January 23, 1996)
The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999
so just live with it, use the setter getter because those are enforced by java surroundings
That's the true what #Peter Lawrey explains about encapsulation.
Only one note: it's more important, when you are working with complex objects (for example in the domain model in a ORM project), when you have attributes that aren't simple Java types. For example:
public class Father {
private List childs = new ArrayList();
public Father() {
// ...
}
private List getChilds() {
return this.childs;
}
public void setChilds(List newChilds) {
this.childs = newChilds;
}
}
public class Child {
private String name;
// ...
private String getName() {
return this.name;
}
public void setName(String newName) {
this.name = newName;
}
}
If you expose one attribute (like the childs attribute in the Father class) as a public, you won't be able to identify what part of your code are setting or changing one property of your exposed attribute (in the case, for example, adding new Child to a Father or even changing the name of a existing Child). In the example, only a Father object can retrieve the childs content and all the rest of the classes can change it, using its setter.
Which of the following is better? Is it even opinion-based or are there any relevant differences? Can one or the other be favored in some scenarios?
public class MyClass {
private Integer myField;
public void setMyField(Integer myField) {
this.myField = myField;
}
public Integer getMyField() {
return myField;
}
}
I need a method to check wether something is allowed or not. Please, let's not talk about the sense of this code example. It's just a minimal example.
Implementation 1
public boolean isAllowed() {
MyEnum.ALLOWED.getInt().equals(getMyField());
}
Implementation 2
public boolean isAllowed() {
MyEnum.ALLOWED.getInt().equals(myField);
}
Edit:
This post does not have an answer in the linked question (see comments to the initial post)
Which of the following is better? Is it even opinion-based or are
there any relevant differences? Can one or the other be favored in
some scenarios?
It is question of good practice I think. The difference is in the readability of the code.
As a general rule, you should avoid indirection if not required.
The current instance of MyClass has the information in one of these fields to implement the operation. It doesn't need to hide its internal state to itself. So in internal, MyClass has no valuable reason to favor the use of the getMyField() over the direct use of the myField field.
The getMyField() accessor is more suitable to be used by clients of the class.
So I think that it is better in any case in your example code :
public boolean isAllowed() {
MyEnum.ALLOWED.getInt().equals(myField);
}
Edit :
Beyond the readability, here is an example why you have no interest to couple the internal state to a public getter.
Suppose during the development phase you remove from the class the public getMyField() method because not need or not needed any longer for clients of the class, if isAllowed() relies on getMyField() in its implementation, it will be broken and you should replace it by myField.
My answer won't be the most informative however it will come from direct experience of dealing with this pattern. When designing an object it is often tempting to directly access member fields rather than rely on accessors. The desire stems from wanting to simplify the object and avoid adding clutter from methods that simple return a value. Taking your example a step further to add context & meaning:
public class MyClassmate {
private Integer age;
public MyClassmate(Integer age) {
this.age = age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
}
Here age is a simple number and it appears unnecessary to add getters/setters around it. If we add the following method you would be tempted to directly access the field since there is no change in behavior:
public Integer calculateScore() {
if(age > 21) return 100 - getNumberOfIncorrectAnswers();
//Add 10% before for younger students
else return (100 - getNumberOfIncorrectAnswers()) + 10;
}
Your object may then grow new features with methods relying on the age field where you continue to use it directly. Later, you might alter the way age is originated and pull the value from across a network. You might not want to incorporate the networking logic in the constructor because it is an expensive operation which should only be triggered as needed. The calculateScore() method could make the network connection and discover the age but then too would all of the other methods that rely on age. But what if calculateScore looked as follows?:
public Integer calculateScore() {
if(getAge() > 21) return 100 - getNumberOfIncorrectAnswers();
//Add 10% before for younger students
else return (100 - getNumberOfIncorrectAnswers()) + 10;
}
You could then enhance the object changing the way it derives age without touching the calculateScore() method. This means your method follows Open Closed Principle (OCP). It is open for enhancement but closed to change, or you didn't have to change the method source in order to change where it gets the age.
Depending on the complexity of your app and object model there may still be times when encapsulated access is overkill but even in these scenarios it is good to understand the tradeoffs of direct field access and these more simplistic scenarios are mostly rare.
In general you should understand that the need for encapsulation is almost never immediate. It appears over time as the object grows and if the object is not setup with encapsulation from its onset it is more expensive to phase it in. That's what makes this approach so difficult to appreciate. It takes experience (i.e. making the typical oversimplification and suffering several times over several years) to feel why encapsulation is necessary. It is not something you can eyeball and detect.
That said, this used to be a much bigger problem than it is today when IDEs were not as full featured. Today you can use the built in encapsulate fields refactoring in certain IDEs like IntelliJ to introduce the pattern as you need it. Even with modern IDEs it is still favorable to practice encapsulation from the onset.
I would recommend using the getter because in certain scenarios, it can have some additional logic (like formatting, checking for nulls and so on). So you may be losing some logic when using the field itself.
To keep a good encapsulation, the first think you need to think is which methods are you going to expose outside your class, if here, for example you are going to use only the is allowed method, I would make public only that method, and define the field in the constructor, if the field is suitable to change then you will need getter/setters but always depends on what do you want to offer from your class. And keep as much encapsulated as you can.
public class MyClass {
private Integer myField;
MyClass(Integer myField){
this.myField = myField;
}
//Only this method is offered nobody need to know you use myField to say true/false
public boolean isAllowed() {
MyEnum.ALLOWED.equals(myField);
}
}
In my Software Engineering courses I was told to realize the "principle of secret". Thus, you should always use getter- and setter-routines. This way you can be sure that nobody accesses the member variable by accident.
Strange functions or objects may never see or even change member variables except you explicitly tell them to do so by setter and getters.
Due to your attribute being private, you can only securely access it within other class using getter or setter methods. So I would say that the best implementation is the one following the encapsulating principle, i.e., the one using the getter instead of accessing directly.
This will prevent data leaks as well.
https://www.tutorialspoint.com/java/java_encapsulation.htm
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = "" instead а = classVariable.getName()
Here is example of class using set and get methods
public class ClassExampe {
String name;
String course;
public String getName ( )
{
return name;
}
public void setName (String studentName)
{
name = studentName;
}
public String getCourse ( )
{
return course;
}
public void setCourse (String studentCourse)
{
course = studentCourse;
}
}
Thanks
Using Getters / Setters vs using Fields
As a rule of thumb:
use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.
The simple rule is: never use direct access (except, of course, when referring to them from inside the class).
field access can't be proxied
you may want to have some event notification
you may want to guard against race conditions
expression languages support setters and getters
theoretically this breaks encapsulation. (If we are pedantic, setter and getter for all fields also breaks encapsulation though)
you may want to perform some extra logic inside the setter or getter, but that is rarely advisable, since consumers expect this to follow the convention - i.e. being a simple getter/setter.
you can specify only a setter or only a getter, thus achieving read-only, or write-only access.
Even if this does not happen that you need any of these, it is not unlikely. And if you start with field access, it will be harder to change.
In Java, using a getter and setter is usually considered best practice.
This is because if you ever need to change your code to do something else when a property is accessed or modified, you can just change it in the existing getter or setter.
I tend to think it causes a bit of clutter for simple objects, but if you have ever had to refactor a public property to a getter and setter to add additional functionality you will see that it can be a pain.
I suspect most will say to always use getters/setters to access private members. It's not necessary, but is considered a "best practice".
One advantage is that you can have more than just simple assignment and returning. Example:
public void setLevel(int lvl)
{
if (lvl<0)
{
this.level=1;
}
else
this.level = lvl;
}
public int getLevel()
{
if (this.someIndicator==4)
return this.level*7.1;
else
return level;
}
Getters and Setters allow you to change the implementation later (e.g. do something more complex), allow you to implement validation rules (e.g. setName throws an exception if the name is not more than 5 characters, whatever.)
You could also choose to add a getter but not a setter so that the variable is like 'read-only'.
That's the theory, however in many cases (e.g. Hibernate using setters) you cannot throw exceptions in setters so you can't do any validation. Normally the value will just be assigned/returned. In some companies I've worked at, it's been mandatory to write getters and setters for all attributes.
In that case, if you want to access an attribute from outside an object, and you want it to be readable/writable, I just use a public attribute. It's less code, and it means you can write things like obj.var += 5 which is easier to read than obj.setVar(obj.getVar() + 5).
If you mean: when to use public accessor methods instead of making the internal, private variable public my answer is "always" unless there is a severe performance reason.
If you mean, call your own get and set methods vs direct access to the vars w/in your class I still say call your own access methods. This way, any conversion, edits or rules you implement as part of get/set get invoked automatically by your own internal calls as well as external callers.
In pure OO languages (for example, Smalltalk) there is no concept of public - all internal vars are private and so you must use accessors. In less pure OO languages, you can make things public - however exposing the internals of your data structures and implementation is an exceptionally bad idea for stability and maintenance in the long run. Look up "tight coupling" for more on this.
Simply put, if you expose internal vars publicly, people can access them directly and if you ever change name or type everything down the line breaks. This is called side effects.
Its a matter of taste, but generally speaking you always should use get/set methods for all properties that are public. But for things like Value Objects (VOs) that you probably are not going to be bothered with for some time you can use public variables without getting too much criticism I think.
In general, you'd want to use setters and getters to give the opportunity to developers reusing your code by modifying it or extending it to add layers of processing and control when accessing and modifying your internal data. This wouldn't be possible in Java when using direct accesses.
Parenthesis: However, it's perfectly possible in other languages, for instance in Scala, when the line between properties and methods can become quite fine. And it's great, as then it doesn't become a coding-problem that gets in the way and it makes usage more transparent.
You can also often consider that in your class you can feel free to access your internal (private or protected) members directly, as you're supposed to know what you're doing, and you don't need to incur the overhead of yet another method call.
In practice, multiple people working on a class might not know what everyone's doing and those lines of integrity checking in your getters and setters might be useful in most cases, while the micro-optimization may not.
Moreover, there's only one way for you to access a variable directly, whereas you can define as many accessors as you want.
Encapsulate the private fields of a class and expose them with getter/setter classes the way you want to.
In Java, I'm wondering why the "length" attribute of the String class isn't private? Isn't it a bad practice according to encapsulation principle? Why is there no method like "getLength()" for instance?
PS: Sorry for my English, I'm still improving it.
In fact, it really is private. Maybe your confusing with the length() method?
There is no public attribute called "length" in java.lang.String. There is a public method "length()", but you can't use it to set the length of the String. It is arguable that they should have called the length() method getLength(), but that was just a choice they made.
Warning: Tangential topic
Public attributes are not inherently evil. The problem with Java is that it doesn't have properties, which allow you to have exposed internal variables at the beginning. When your requirements for encapsulation grow stronger you can change the internals of the class without affecting its signature/API. With properties, you can have your cake and eat it too, you can access a property as a variable, but being unable to set/assign to it outside the class.
Java programmers get around this by creating from the start getters and setters for every public facing attribute, whether it has any kind of processing or not, just in case. I've seen Java programmers starting on other languages that do have properties doing the same sin of using getters and settersthing . Please, if you ever go to another language, don't bring all the misconceptions from Java born out of implementation details of the JVM.
Encapsulation != getters && setters.
</rant>
I think you mean the array objects, right?
Personally I think it's all-right to have (preferably final) fields on classes that are just glorified structs. E.g., I would rather do
public Person {
final String name;
final String surname;
public Person(String name, String surname) {
this.name = name;
this.surname = surname;
}
}
than the same thing with getters and setters.