views:

170

answers:

6

Ok, so I am about to embarrass my self here but I am working on a project that I will need to get some help on so I need to get some conventions down so I don't look too stupid. I have only been doing java for 2 months and 100% of that has been on Android.

I need some help understanding setting up variables and why I should do it a certain way.

Here is an example of my variables list for a class:

    Button listen,feed;
Context context = this;
int totalSize = 0;
int downloadedSize = 0;
SeekBar seek;
String[] feedContent = new String[1000];
String[] feedItems = new String[1000];
ListView podcast_list = null;
HtmlGrabber html = new HtmlGrabber();
String pkg = "com.TwitForAndroid";
TextView progress = null;
long cp = 0;
long tp = 0;
String source = null;
 String pageContent = null;
 String pageName = "http://www.shanescode.com";
 DataBaseHelper mdbHelper = new DataBaseHelper(this);
int songdur = 0;

So all of these are variables that I want to use in all through the whole class. Why would I make something a static, or a final. I understand Public but why make something private?

Thanks for your help and please don't be too harsh. I just need some clarification.

+1  A: 

static = same for all instances of a class.

final = unchanging (reference) for a particular instance.

If you needed some field (aka a class variable) to be shared by all instances of a class (e.g., a constant) then you might make it static.

If you know some field is immutable (at least, it's reference is immutable) in an instance, then it is good practice to make it final. Again, constants would be a good example of a field to make final; anything that is constant within an instance from construction time on is also a good candidate for final.

A search for "java final static" gives pretty useful further reference on the use of those keywords.


The use of the private keyword controls what can accessed by other classes. I'd say it's biggest use is to help developers "do the right thing" - instead of accessing the internals of the implementation of another class, which could produce all sorts of unwanted behavior, it forces using accessor/mutator methods, which the class implementor can use to enforce the appropriate constraints.

Carl
A: 

I don't know why you would make anything private.

Folks will chime in and say that private is a Very Important Thing.

Some folks will claim that you can't do encapsulation without private. Most of this seems to be privacy for privacy's sake.

If you are selling your code to someone else, then you must carefully separate the interface elements of your class from the implementation details of your class. In this case, you want to make the implementation private (or protected) so that -- for legal purposes -- the code you sell doesn't expose too much of the implementation details.

Otherwise, if you're not selling it, don't waste a lot of time on private.

Invest your time in separating Interface from Implementation. Document the Interface portions carefully to be sure you're playing by the rules. Clearly and cleanly keep the implementation details separate. Consider using private as a way to have the compiler "look over your shoulder" to be sure you've really separated interface from implementation.

S.Lott
Yes, private (and protected) help the compiler enforce the separation between interface and implementation, and between different components of each. That's exactly why visibility is a Very Important Thing. It's not just about selling your code - good visibility practices help anyone using your code (whether other programmers or even yourself) to understand the structure of the program.
tlayton
@tlayton: I think I agree with S.Lott - it seems to me what he's saying is that `private` can be a Useful Thing, even a Very Useful Thing - but that rigorous enforcement of `private` for the sake of using the keyword tends to happen to the detriment of getting things done (overall, not just short term), and that such rigorous enforcement happens when we think of `private` as Very Important instead of Very Useful.The flipside being that rigorous use can be good practice, and good practice makes good execution.
Carl
There's not a lot of time wasted on 'private'. You just type the word and you're done :)A useful technique is to start by default with everything marked private, and then only change the absolute minimum to public to get the class to work as expected. This way you've still got good encapsulation and you don't have burn many calories on it.
Keith Twombley
@Kieth Twombley: Starting with all private doesn't give "good" encapsulation. It just gives a class that's hard to use until you start making things public. "Good" encapsulation is "good" design. All the time wasted trying to get unit tests to work with excessive private declarations is -- well -- wasted. The use case for private is often grossly over-stated, leading to time lost in writing effective unit tests.
S.Lott
+6  A: 

These words all alter the way the variable to which they are applied can be used in code.

static means that the variable will only be created once for the entire class, rather than one for each different instance of that class.

public class MyClass{
    public static int myNumber;
}

In this case the variable is accessed as MyClass.myNumber, rather than through an instance of MyClass. Static variables are used when you want to store data about the class as a whole rather than about an individual instance.

final prevents the variable's value from changing after it is set the first time. It must be given an initial value either as part of its declaration:

public final int myNumber = 3;

or as part of the class's constructor:

public MyClass(int number){
    this.myNumber = 3;

Once this is done, the variable's value cannot be changed. Keep in mind, though, that if the variable is storing an object this does not prevent the object's variable from being changed. This keyword is used to keep a piece of data constant, which can make writing code using that data much easier.

private modifies the visibility of the variable. A private variable can be accessed by the instance which contains it, but not outside that:

public class MyClass{
    private int myNumber;

    public void changeNumber(int number){
        this.myNumber = number;  //this works
    }
}

MyClass myInstance = new MyClass();
myInstance.myNumber = 3;  //This does not work
myInstance.changeNumber(3) //This works

Visibility is used to control how a class's variables can be used by other code. This is very important when writing code which will be used by other programmers, in order to control how they can access the internal structure of your classes. Public and private are actually only two of the four possible levels of visibility in Java: the others are protected and "no (visibility) modifier" (a.k.a not public or private or protected). The differences between these four levels is detailed here.

tlayton
+1  A: 

Private

The idea behind using private is information hiding. Forget about software for a second; imagine a piece of hardware, like an X-Box or something. Somewhere on it, it has a little hatch to access the inside, usually sporting a sticker: "open this up and warranty is void."

Using private is sticking a sticker like that in your software component; some things are 'inside' only, and while it would be easy for anyone to open it up and play with the inside anyways, you're letting them know that if they do, you're not responsible for the unexpected behavior that results.

Static

The static keyword does not mean "same for all instances of a class"; that's a simplification. Rather, it is the antonym of "dynamic". Using the static keyword means "There is no dynamic dispatching on this member." This means that the compiler and not the run-time determines what code executes when you call this method.

Since thee are no instances of objects at compile-time this means that a static member has no access to an instance.

An example:

public class Cat {
    public static void speak() { System.out.println("meow"); }
}

public class Lion extends Cat {
    public static void speak() { System.out.println("ROAR"); }
}

// ...
public static void main(String argv[]) {
    Cat c = new Lion();
    c.speak();
}

The above prints "meow" - not "roar" - because speak is a static member, and the declared type of c is Cat, so the compiler builds in such a way that Cat.speak is executed, not Lion.speak. Were there dynamic dispatching on static members, then Lion.speak would execute, as the run-time type of c is Lion.

LeguRi
A: 

One of the aspects of the object oriented approach that has made it so wildly popular is that you can hide your variables inside of a class. The class becomes like a container. Now you as the programmer get to decide how you want the users of your class to interact with it. In Java, the tradition is to provide an API -- a public interface for your class using methods of the class.

To make this approach work, you declare your variables as private ( which means only methods within your class can access them ) and then provide other methods to access them. For example,

private int someNumber;

This variable can only be accessed from within your class. Do you think others might need access to it from outside of the class? You would create a method to allow access:

public int getSomeNumber()
{
     return someNumber;
}

Perhaps users of your class will also need the ability to set someNumber as well. In that case, you provide a method to do that as well:

public void setSomeNumber( int someNumber )
{
     this.someNumber = someNumber;
}

Why all of this work just to get access to a class member that you could just as easily declare as public? If you do it using this approach, you have control over how others access the data in your class. Imagine that you want to make sure that someNumber only gets set to be a number < 100. You can provide that check in your setSomeNumber method. By declaring your variables to have private access, you protect your class from getting used incorrectly, and make it easier on everyone who needs to use it -- including yourself!

Declaring a variable to have static access means that you do not need an instance of the class to access the variable. In Java, generally you write a class and then create an instance of it. You can have as many instances of that class as you want, and they all keep track of their own data. You can also declare variables that are part of the class itself, and this is where the static keyword comes in. If you create a variable...

static int classVariable = 0;

the variable can be accessed without a class instance. For example, you might see this done from time to time:

public static final int MY_CONSTANT = 1;

While there are better ways to do this now, it is still a common pattern. You use this variable without any instance of the class like this:

myInstance.setSomeNumber( MyClass.MY_CONSTANT );

java.awt.Color uses static variables this way. You can also declare methods to be static ( look at public static void main, the starting point for your programs ). Statics are useful, but use them sparingly because creating instances of classes can often result in better designs.

Finally ( pun intended ), why would you ever want to declare a variable to be final? If you know that the value should never change, declaring it as final means that if you write some code that tries to change that value, the compiler will start complaining. This again helps protect from making silly mistakes that can add up to really annoying bugs.

If you look at the static variable example above, the final keyword is also used. This is a time when you have decided that you want to make a variable public, but also want to protect it from being changed. You do this by making it public and final.

matsuzine
+1  A: 

Another thing that might trip you up is this:

Not everything has to be a class level variable; you should have a variable defined for the smallest scope it needs to be defined.

So as an example, suppose your class only has one method which uses your TextView progress variable. Move that declaration into the method that needs it. This way it tidies things up and helps you make more robust code by separating out things that are really separate.

Keith Twombley