strauberry
strauberry

Reputation: 4199

Why can attributes in Java be public?

As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the only interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?

Upvotes: 45

Views: 16536

Answers (12)

jgleoj23
jgleoj23

Reputation: 262

I really can't think of a good reason for not using getters and setters outside of laziness. Effective Java, which is widely regarded as one of the best java books ever, says to always use getters and setters. If you don't need to hear about why you should always use getters and setters skip this paragraph. I disagree with the number 1 answer's example of a Point as a time to not use getters and setters. There are several issues with this. What if you needed to change the type of the number. For example, one time when I was experimenting with graphics I found that I frequently changed my mind as to weather I want to store the location in a java Shape or directly as an int like he demonstrated. If I didn't use getters and setters and I changed this I would have to change all the code that used the location. However, if I didn't I could just change the getter and setter.

Getters and setters are a pain in Java. In Scala you can create public data members and then getters and or setters later with out changing the API. This gives you the best of both worlds! Perhaps, Java will fix this one day.

Upvotes: -1

Hazok
Hazok

Reputation: 5583

To use public or not really depends on whether there is an invariant to maintain. For example, a pure data object does not restrict state transition in any fashion, so it does not make sense to encapsulate the members with a bunch of accessors that offer no more functionality that exposing the data member as public.

If you have both a getter and setter for a particular non-private data member that provides no more functionality than getting and setting, then you might want to reevaluate your design or make the member public.

Upvotes: 1

Diego
Diego

Reputation: 1569

Accesibility modifiers are an implementation of the concept of encapsulation in OO languages (I see this implementation as a way to relax this concept and allow some flexibility). There are pure OO languages that doesn't have accesibility modifiers i.e. Smalltalk. In this language all the state (instance variables) is private and all the methods are public, the only way you have to modify or query the state of an object is through its instance methods. The absence of accesibility modifiers for methods force the developers to adopt certain conventions, for instance, methods in a private protocol (protocols are a way to organize methods in a class) should not be used outside the class, but no construct of the language will enforce this, if you want to you can call those methods.

Upvotes: 0

ZaoTaoBao
ZaoTaoBao

Reputation: 2615

I'm just a beginner, but if public statement doesn't exists, the java development will be really complicated to understand. Because we use public, private and others statements to simplify the understanding of code, like jars that we use and others have created. That I wanna say is that we don't need to invent, we need to learn and carry on.

I hope apologize from my english, I'm trying to improve and I hope to write clearly in the future.

Upvotes: -1

samridhi
samridhi

Reputation: 500

I believe data encapsulation is offered more like an add-on feature and not a compulsory requirement or rule, so the coder is given the freedom to use his/her wisdom to apply the features and tweak them as per their needs.Hence, flexible it is!

A related example can be one given by @Oli Charlesworth

Upvotes: 0

Edwin Buck
Edwin Buck

Reputation: 70909

Java is a branch from the C style-syntax languages. Those languages supported structs which were fixed offset aliases for a block of memory that was generally determined to be considered "one item". In other words, data structures were implemented with structs.

While using a struct directly violates the encapsulation goals of Object Oriented Programming, when Java was first released most people were far more competent in Iterative (procedural) programming. By exposing members as public you can effectively use a Java class the same way you might use a C struct even though the underlying implementations of the two envrionments were drastically different.

There are some scenarios where you can even do this with proper encapsulation. For example, many data structure consist of nodes of two or more pointers, one to point to the "contained" data, and one or more to point to the "other" connections to the rest of the data structure. In such a case, you might create a private class that has not visibility outside of the "data structure" class (like an inner class) and since all of your code to walk the structure is contained within the same .java file, you might remove the .getNext() methods of the inner class as a performance optimization.

Upvotes: 2

Dan
Dan

Reputation: 2759

Object Oriented design has no requirement of encapsulation. That is a best practice in languages like Java that has far more to do with the language's design than OO.

It is only a best practice to always encapsulate in Java for one simple reason. If you don't encapsulate, you can't later encapsulate without changing an object's signature. For instance, if your employee has a name, and you make it public, it is employee.name. If you later want to encapsulate it, you end up with employee.getName() and employee.setName(). this will of course break any code using your Employee class. Thus, in Java it is best practice to encapsulate everything, so that you never have to change an object's signature.

Some other OO languages (ActionScript3, C#, etc) support true properties, where adding a getter/setter does not affect the signature. In this case, if you have a getter or setter, it replaces the public property with the same signature, so you can easily switch back and forth without breaking code. In these languages, the practice of always encapsulating is no longer necessary.

Upvotes: 3

Jomoos
Jomoos

Reputation: 13083

Discussing good side of public variables... Like it... :)

There can be many reasons to use public variables. Let's check them one by one:

Performance

Although rare, there will be some situations in which it matters. The overhead of method call will have to be avoided in some cases.

Constants

We may use public variables for constants, which cannot be changed after it is initialized in constructor. It helps performance too. Sometimes these may be static constants, like connection string to the database. For example,

public static final String ACCEPTABLE_PUBLIC = "Acceptable public variable";

Other Cases

There are some cases when public makes no difference or having a getter and setter is unnecessary. A good example with Point is already written as answer.

Upvotes: 2

mre
mre

Reputation: 44240

Not all classes follow the encapsulation paradigm (e.g. factory classes). To me, this increases flexibility. And anyway, it's the responsibility of the programmer, not the language, to scope appropriately.

Upvotes: 5

Hot Licks
Hot Licks

Reputation: 47699

Because rigid "data encapsulation" is not the only paradigm, nor a mandatory feature of object orientation.

And, more to the point, if one has a data attribute that has a public setter method and a public getter method, and the methods do nothing other than actually set/get the attribute, what's the point of keeping it private?

Upvotes: 14

duffymo
duffymo

Reputation: 308743

I think it's possible because every rule has its exception, every best practice can be overridden in certain cases.

For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.

I'll point out that this situation is true in other languages besides Java: C++, C#, etc.

Languages need not always protect us from ourselves.

In Oli's example, what's the harm if I write it this way?

public class Point {
   public final int x;
   public final int y;

   public Point(int p, int q) {
      this.x = p;
      this.y = q;
   } 
}

It's immutable and thread safe. The data members might be public, but you can't hurt them.

Besides, it's a dirty little secret that "private" isn't really private in Java. You can always use reflection to get around it.

So relax. It's not so bad.

Upvotes: 80

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

For flexibility. It would be a massive pain if I wasn't able to write:

class Point {
    public int x;
    public int y;
}

There is precious little advantage to hide this behind getters and setters.

Upvotes: 53

Related Questions