Results 1 to 5 of 5
- 10-11-2011, 11:21 PM #1
Member
- Join Date
- Sep 2010
- Posts
- 30
- Rep Power
- 0
Is it bad practice to make attributes public so other classes can call their methods?
This is for a game I need to code, an Oregon Trail style game, but I've always been curious about this.
For example, my main method has the Wagon object, and the wagon is holding the different people. If I want to modify a Persons health with setHealth(int h), could I just make the people a public attribute (or array) and the main method could directly modify them?
This seems a lot easier, and I won't have to put a new setter in Wagon just to modify its contents.
thanks for the help guys
- 10-11-2011, 11:35 PM #2
Senior Member
- Join Date
- Oct 2011
- Posts
- 115
- Rep Power
- 0
Re: Is it bad practice to make attributes public so other classes can call their meth
Good question! I am wondering the same thing.
-
Re: Is it bad practice to make attributes public so other classes can call their meth
It's usually a good practice to use getters and setters. This allows you to fully control visibility of your properties and allows you to do validity checking prior to setting a property. It also gives other flexibility such as allowing you to later make your property a "bound" property by using PropertyChangeSupport so that other classes (or this class) can listen and react to changes in this property -- something that I've found to be very useful.
- 10-11-2011, 11:46 PM #4
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,604
- Rep Power
- 5
Re: Is it bad practice to make attributes public so other classes can call their meth
Controlling Access to Members of a Class (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
To quote the advice from the article above:
In other words - it is good practice to encapsulate variables - making variables public can cause all sorts of problems when it comes to a good deal of things, especially code maintenance.Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
- 10-11-2011, 11:48 PM #5
Senior Member
- Join Date
- Oct 2011
- Posts
- 115
- Rep Power
- 0
Similar Threads
-
Call Static Methods Outside Classes
By Insomniac Riot in forum New To JavaReplies: 4Last Post: 05-11-2010, 10:03 PM -
Methods and Attributes Layout
By Bascotie in forum New To JavaReplies: 2Last Post: 01-16-2009, 12:53 AM -
Classes with object attributes
By RRasco in forum New To JavaReplies: 5Last Post: 11-25-2008, 12:07 AM -
[SOLVED] Best practice for creating test classes
By mwildam in forum New To JavaReplies: 3Last Post: 08-27-2008, 04:59 PM -
How to call methods of different classes
By adeeb in forum New To JavaReplies: 2Last Post: 06-06-2008, 06:08 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks