wood burning stoves 2.0*
The moose likes Java in General and the fly likes Why public modifiers for fields? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Why public modifiers for fields?" Watch "Why public modifiers for fields?" New topic
Author

Why public modifiers for fields?

N Az
Greenhorn

Joined: Jan 28, 2007
Posts: 6
Hi,

I would like to know as to why JAVA has public access modifiers for fields. It is always suggested that the fields should be private and only the methods should be provided to modify these fields. If this is the preferred one then why at all the public has been provided for fields? Any specific scenario where the methods will not be useful?

Regards
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Well, you wouldn't want to disallow "public static final" fields, or it would become very cumbersome to define constants. I do occasionally have "public final" fields that are not "static", but it's harder to argue that's a good idea, really.

It seems to me that there are no really good reasons ever to have public non-final fields, but it's not clear that's a reason to absolutely ban them.

A ban on them couldn't be introduced now, because of the need for backwards compatibility. Anyway, Java doesn't try to enforce best practice in every area, so one could argue it's just up to the programmer not to do silly things like exposing internal data to all comers.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Amit Biswas
Ranch Hand

Joined: Jun 01, 2006
Posts: 52
I have typically seen public access modifiers being used for constant fields. These are typically like
public static final Double PI_CONSTANT = "3.142857" ;
In a situation where you have a lot of constant values you can use the public access modifiers and avoid hardcoding. One of the favorite places to do that is in some kind of contexts, say for example the HTTPSession. If you are adding placing a certain value in the session and the key is a hardcoded value, it may not be very readable. But if you have a constants class/interface and declare your key there, then it is more easily understood. In fact, in interfaces you can only add constants as shown above.
Now , analysing the second part of your question. Well, firstly it should be understood that it is just a good and recommended design practice to have the instance variables as private fields and getters/setter methods to expose it outside. But there may be situations where this approachmay not be suitable. Let me confess that currently I am not aware of any such situation where having a instance variable as private can create problems. But in justification of Java Specification, I would assume there may be certain exceptional cases.
To conclude, public access modifiers are typically used in constants. Public access modifiers are mandatory for field in interfaces. You can also think of a situation where a class is being inherited outside its package and there exists a variable that has to be overridden. In this case too, you need a public field modifier.

Hope that gives you some pointers!
N Az
Greenhorn

Joined: Jan 28, 2007
Posts: 6
Thanks for your input guys... I am a novice in this field of java and am trying to learn it and understand the logic as to why the things have been defined the way they are....

Now, I understand that public is mostly used (in terms of fields) with static

But, this raises another question as to do we need(or suggest to use) private for static fiels also??? If no, then static may had been defined in such a way that it is by default "public static" and then doing this might have helped in enforcing two standards , with regard to public and static separately....
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I see two reasons:

First, disallowing the public access modifier for fields - or probably just for non-static, non-final fields - would add an unneeded conceptual complexity to the language.

Second, not making feels public is more of a heuristic than a hard and fast rule. It is a good heuristic because it conforms to the principle of information hiding. It doesn't apply, though, where information hiding is in fact not needed - a popular example that comes to mind are Data Transfer Objects, which are all about exposing data (in fact it could be argued that calling them "objects" is kind of a stretch).

Having said that, Smalltalk, the poster child of OO languages, doesn't have any access modifiers in the language - all fields are automatically private, all methods public. Seems to work just fine, too (and is even simpler than Javas model).


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Nayab Azeem:
But, this raises another question as to do we need(or suggest to use) private for static fiels also??? If no, then static may had been defined in such a way that it is by default "public static" and then doing this might have helped in enforcing two standards , with regard to public and static separately....


Static non-final fields are subject to the same arguments as instance non-final fields. It is very difficult to think of a good reason not to make them private. Any access modifier is, however, legal in Java.

It is definitely useful to have the full range of access modifiers available for static final fields. Constants - which is what these are - can entirely reasonably be used in just the class (private), the package, the inheritance hierarchy (protected) or everywhere (public).
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Amit Biswas:
Public access modifiers are mandatory for field in interfaces.


Not quite true.

Public access modifier is implied in interfaces. It is legal to declare any field or method in an interface explicitly as "public". It is legal to give no explicit access modifier, in which case "public" is assumed. It is not legal to give any other access modifier, as that would conflict with the implied "public".

I used to put "public" explicitly, but I've changed to giving no access modifiers in interfaces. There are probably plenty of people on each side of that argument, but I believe that few people would be very bothered by either approach.

Note finally that any fields in interfaces have to be "static" and "final" - i.e. constant. However, these modifiers aren't implied AFAIK, so you have to give them explicitly.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Nayab Azeem:
But, this raises another question as to do we need(or suggest to use) private for static fiels also??? If no, then static may had been defined in such a way that it is by default "public static" and then doing this might have helped in enforcing two standards , with regard to public and static separately....


Sure it makes sense to have "private static". First, some constants are better not exposed to the public, second not all static fields are also final (and therefore constants).

Anyway, I'm not very much for a language to "enforce" standards. I'm not at all troubled by the Smalltalk way, because it makes the language much simpler. I would be troubled by your proposal, because it would make the language more complex (or so it seems to me), and at the same time reduces my flexibility to use it for unusual situations (where the "standard" doesn't really apply).

Does that sound reasonable?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39044
    
  23
I think the correct answer is that Java permits lots of things which we don't usually do. There are a few classes in the API which have public fields, eg java.awt.GridBagConstraints, so the designers of the API actually permit you to write something like:-Yes, you can have public default protected and private access to any class member.

Yes, you can have private static fields. Let's say this is an example from a game:-This does not allow another class to alter the count variable, but the number of Ogres is available via the getCount method. You notice that count represents how many living Ogres there are, and that their attack behaviour is different if there are more than 5 of them.
An example of use of a private static variable, which I hoep has helped you.

CR
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Peter Chase]: Note finally that any fields in interfaces have to be "static" and "final" - i.e. constant. However, these modifiers aren't implied AFAIK, so you have to give them explicitly.

Any fields in an interface are implicitly public, static, and final - you don't have to specify those modifiers.


"I'm not back." - Bill Harding, Twister
Ricky Clarkson
Ranch Hand

Joined: Jul 27, 2006
Posts: 131
When a class is only used within one codebase, you can automatically refactor it to later 'encapsulate' the data with get/set methods. That means the simplest way to do it, for an internal-only class, is to make the fields public, until you have a reason not to (for example, you want to validate to make sure the field can never be null, negative, etc.).

This gets a bit harder with code that is used by more than one project - you need to design so that change of implementation affects clients as little as possible.

If Java had Delphi-like properties from the start, there would have been no argument in favour of public non-final fields, as properties would be superior. There are a few Javalobby threads on this.
N Az
Greenhorn

Joined: Jan 28, 2007
Posts: 6
Ritchie, I was not doubting if we can have private static or not. Was just wondering if it is really required or not. Your example presents a gud scenario where we need it.

Thanks guys for all your inputs. It really helps a lot in understanding things...

As for making things complex or simple, it is more of a habit and dealing with the constraints.....emember we had moved from multiple inheritance to interfaces...
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Often, for in-package objects I may simply expose the fields directly rather than having getters and setters. This is only on classes that have package scope. And sometimes I do use value objects to transfer my data, which may have public fields. I only seem to use it when I am moving 'data'. Otherwise all my fields are private. Except now that Eclipse is warning me about inner classes accessing private fields requires some JVM trickery I am making many of them package scope.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Jim Yingst:
[Peter Chase]: Note finally that any fields in interfaces have to be "static" and "final" - i.e. constant. However, these modifiers aren't implied AFAIK, so you have to give them explicitly.

Any fields in an interface are implicitly public, static, and final - you don't have to specify those modifiers.


Serves me right for not checking. Well, that makes my participation in the topic worthwhile for me, as I have learnt something new. Thanks.

FYI the reason why I thought "public" was implied and the others weren't is that our automatic code style checker complains if you put "public" in an interface (because it's implied anyway), but does not complain if you declare the fields "static" or "final".
[ February 26, 2007: Message edited by: Peter Chase ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39044
    
  23
Your example presents a gud scenario where we need it.
Shucks, you have got me all embarrassed. No, seriously we are only too pleased to help.

Mr Gilbert: When you say you are getting Eclipse warnings about access to private members from inner classes, are you only getting the yellow triangle? That means you have Eclipse set in fusspot mode, which is the way I like it too.
But I think the warning is only that one can get better performance by giving the fields less restrictive access. I usually get that warning with ActionListener or similar inner classes, so what is a microsecond against the 0.4 seconds it takes to click the mouse? I tend to note those warnings and take no action.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

You can use public access to fields for performance reasons, and lean code:


If you got a lot of 'x'es (field.x, enemy.x, old.x, new.x, screen.x, fruit.x ...), using just x and y might be confusing.
Using position.horizontal.increment () instead of ++pos.x; is not better to understand, not better to write.
Access to the position.x is still restricted, since access to postion is restricted.

If the code is using x and y excessively, and doesn't need boundary-checks etc. (which doesn't seems to be correct for my example), direct access might be appropriate.

Just my 2�.


http://home.arcor.de/hirnstrom/bewerbung
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
In this example, the "public" on the fields makes no difference. The outer class can access inner class members, whatever their access modifier.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Peter Chase:
In this example, the "public" on the fields makes no difference. The outer class can access inner class members, whatever their access modifier.


That's true at the source level.

At the byte code level, though, there are no inner classes, only top level classes. To still make it work, the compiler has to introduce synthetic accessor methods for the fields if they are not declared public.
Amit Biswas
Ranch Hand

Joined: Jun 01, 2006
Posts: 52
Not quite true.

Public access modifier is implied in interfaces. It is legal to declare any field or method in an interface explicitly as "public".


All I meant is the fields/methods in interfaces are always public whether you key-in the keyword "public" or not. Also all methods in interfaces are abstract regardless of whether you explicitly type "abstract" or not.
 
GeeCON Prague 2014
 
subject: Why public modifiers for fields?