• Post Reply Bookmark Topic Watch Topic
  • New Topic

referencing variables  RSS feed

 
Tyler Jordan
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a structure with 3 seperate files with the classes.
Topology Class
Device Class
Widget Class
I create an instance of Device class from Topology class and an instance of Widget Class from Device class. (while inside the original instance I created for Device class)
Can I reference global variables I create inside Widget class directly? With a form like:

Or do I need to create a method inside the Widget class and return the varible that way.

Thanks for any help!
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The norm is your 2nd approach. Make your variables private in your class. Then provide public methods to get/set the variables.
 
Tony Williams
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While you can access non-private data members from outside the class it is usually not the best design. First a review of access control:
int var; // default - can access from any class in same package
private int var; // can access only from within this class
public int var; // can access from any class
protected int var; // can access from any subclass of this class
It is usually a good idea to make your data members private and provide accessors. These are often called "setters" and "getters" due to their common naming convention. Here's an example.
private int var;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
These accessors provide you with a way to control the legal values that are allowed in your private data members. For example, if you only want positive integers, you can change setVar as so:
public void setVar(int var) {
if(var > 0)
this.var = var;
}
Now you have control over the state of your objects and have eliminated a few potential bugs arising from indiscriminate access to private data.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!