• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why public modifiers for fields?

 
N Az
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Amit Biswas
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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�.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic