Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2005

Tip: Looking for answers? Try searching our database.

Public vs private instance fields

Thread view: 
Brian Munroe - 29 Mar 2005 20:19 GMT
Newbie Java/OOP question here, which is more correct?

1) Define a public instance field and access it like:

Object o = new Object()
o.field1 = "hello";
System.out.println(o.field1);

2) Define a private instance field and use set/get methods to access
it:

Object o = new Object()
o.setField1("hello");
System.out.println(o.getField1());

I prefer to make it public, less typing all around, but being my luck,
it isn't the correct way either :)

thanks

-- brian
Bryce - 29 Mar 2005 20:34 GMT
>Newbie Java/OOP question here, which is more correct?
>
[quoted text clipped - 13 lines]
>I prefer to make it public, less typing all around, but being my luck,
>it isn't the correct way either :)

Correct is what you make of it...

But.. Generally, using accessors and mutators (get/set methods) is
considered more OO. For instance, you might want to make an instance
variable readonly, so just use a get method. YMMV.

Plus, as for typing, any decent Java IDE should generate the get/set
methods for you.

--
now with more cowbell
Brian Munroe - 29 Mar 2005 21:01 GMT
> For instance, you might want to make an instance
> variable readonly, so just use a get method. YMMV.

I knew there was a reason why it was better, I just couldn't think of
one!

> Plus, as for typing, any decent Java IDE should generate the get/set
> methods for you.

I just tried this in Eclipse, neat!

thanks

-- brian


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.