Related
Sometimes I see something like :
public class MainActivity extends Activity
{
public static final String url_google = "http://www.google.com";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
What I actually don't get, is why using public static final , and not public final or final
I'm speaking very broadly, but if it's final, you only need one instance of it anyways, so it saves memory by making it static.
To be more specific, the final keyword means that whatever the variable stores cannot be changed. This means that once the variable has a value, you may use the variable, but you cannot modify it in any way. Commonly, to give a value to a final variable, you do so right from the declaration eg final int variable = 12. As you can see I used an int for my example, however you can use anything, including reference variables. Reference variables, are special though, because you cannot change what the variable points to, but you can change the Object itself (such as using get/set methods).
What this boils down to though, is that once you have made a final variable it occupies space in memory. Since we can't modify this variable further, why should we recreate it every time our Class is instantiated? So we use the static keyword. This allows the variable to be created once, and only once in memory.
There are though, some specific cases in which you would want to not use static and use just final. One example may be time sensitive variables, such as storing the time of Object instantiation.
static means that only one url_google will be created. If it is an instance field (not static), then a new url_google will be created with each instance of the activity, and what you actually need is only one copy of url_google.
The Java final keyword is very loosely used to indicate that something "cannot change".
It has nothing to do with the static keyword which indicated it's a “class variable” meaning all instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create a instance.
They have different meaning and can be used together or separately.
I think A--C's answer is misleading: "I'm speaking very broadly, but if it's final, you only need one instance of it anyways, so it saves memory by making it static."
As others pointed out he's mixing static and final which are two very different things. It's not broadly speaking IMHO but not precise enough, especially when explaining fundamental concepts.
Static variables are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
Final variables on the other side are variables that can only be initialized once. Their values don't have to be known at compile time but can be set at run time.
If a final variable is an instance variable there can be many instances of this variable, all with different values.
A static final variable is a constant because there's just one and it cannot be altered at run time once it has been initialized. In Java at least the value doesn't have to be known at compile time.
Now that is all very theoretic, so let's make an example to show the use for these types of variables:
public class Circle implements Serializable {
private static final long serialVersionUID = -1990742486979833728L;
private static int sNrOfCircles;
private final double mArea;
public Circle(double radius) {
sNrOfCircles++;
mArea = radius*radius*Math.PI;
}
}
serialVersionUID associates a version number with the Circle class used during deserialization to verify that the sender and receiver have loaded classes for that object that are compatible with respect to serialization. serialVersionUID never changes and is the same for all instances of Circle.
sNrOfCircles counts the number of Circle instances. It changes with every new instance of Circle (while serialVersionUID never does).
mArea defines the area of the Circle. It also changes with every instance of Circle but compared to sNrOfCircles it's associated with the Circle object and not the Circle class and also it can't be altered while sNrOfCircles will change when another Circle object is created.
To put it simple: use static if it's a Class attribute (how many Circles do we have?), use final if the value won't change once it's initialized (area of a circle with a given radius) and use static final if it's both.
The main reason would be that you an access the value without needing an actual instance of the class.
In your example, any code could access the url_google value, without needing an instance of MainActivity.
Could I make static property final when it is defined in constructor, not on declaration?
I know how can I create my custom class that creates immutable instances.
But is it possible to make immutable object of some standard class?
For example Object, JPanel, Calendar or anything else?
But is it possible to make immutable object of some standard class?
No. There's nothing in Java to support this. All you can do is limit how widely published the reference is, and make sure that any code which has access to it doesn't mutate it. You could create your own wrapper type which only exposes read-only operations, and expose that freely, of course.
EDIT: As noted in comments, there's some support for this within the JDK, for collections - and Guava provides more thoroughly immutable collections and builders for them. However, there's nothing general-purpose to take an object of any mutable type and give you back an immutable view of it.
Static Initialization
Could I make static property final when it is defined in constructor,
not on declaration?
You can only assign static final attributes when they are declared or in a static { } block. By the time the constructor gets called it is too late, the reference will already have been assigned to null as all static code is evaluated first.
As in private static final String s = "Hello World!";
or
private static final String s;
static { s = "Hello World!"; }
Dynamic Proxies
I know how can I create my custom class that creates immutable
instances. But is it possible to make immutable object of some
standard class? For example Object, JPanel, Calendar or anything else?
You can use Dynamic Proxys to have all mutating methods like anything that is setXXX() for example throw an UnsupportedOperationException instead of what they actually do. I consider this approach semi-hackish, but they put this in to Java for situations just like this, so it was designed just for these types of problems.
Depending on the interfaces involved and the naming conventions it might be just as much work as just manually creating wrappers yourself.
So it is definitely possible in Java, here is an example of disabling the .add() method on a List which is the start of making a class immutable.
Hitting the metal
You can do the same thing and even more with CGLib but there is no real easy to use documentation or examples, so I only mention it here for completeness; as well as this would be the only way to modify the behavior of final classes. JMock does this to provide Mock implementations of final classes.. This is deep magic, but if you really need to do this, it is possible.
For the first part of the question, if I'm reading it right:
class Test{
public static final int x;
public final int y;
public Test(){
y = 16;
}
static{
x = 42;
}
}
Basically a static final field can also be initialized in a static initializer block, and a final field can be initialized in a constructor.
Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to define a protocol behavior for the implementing class which implies that the class that implements (inherits) an interface must incorporate all of the members of that interface.
I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?
A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?
The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.
public static void main(String args[])
{
final int a=0; //ok
int b=1; //ok
static int c=2; //wrong
final static int x=0; //wrong
}
You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.
Anyways, these are the concepts you are mixing up:
variables
final variables
fields
final fields
static fields
final static fields
The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).
Let's try to rapidly describe them.
variables are declared in methods, and used as some kind of mutable local storage (int x; x = 5; x++)
final variables are also declared in methods, and are used as an immutable local storage (final int y; y = 0; y++; // won't compile). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final. Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).
fields define the mutable state of objects, and are declared in classes (class x { int myField; }).
final fields define the immutable state of objects, are declared in classes and must be initialized before the constructor finishes (class x { final int myField = 5; }). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).
static fields are shared among all instances of any class. You can think of them as some kind of global mutable storage (class x { static int globalField = 5; }). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } }, here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x()). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).
final static fields are global constants (class MyConstants { public static final double PI = 3.1415926535897932384626433; }).
There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.
Finally, there are also other keywords that might be used with fields, like transient, volatile and the access levels (public, protected, private). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).
Static members are those which can be accessed without creating an object. This means that those are class members and nothing to do with any instances. and hence can not be defined in the method.
Final in other terms, is a constant (as in C). You can have final variable inside the method as well as at class level. If you put final as static it becomes "a class member which is constant".
I'm unable to differentiate between a final and a final static member.
The final static member is the one which is a static member declared
as final or something else? In which particular situations should they
be used specifically?
Use a final static when you want it to be static. Use a final (non-static) when you don't want it to be static.
A static variable or a final static variable can never be declared
inside a method neither inside a static method nor inside an instance
method. Why?
Design decision. There's just no way to answer that without asking James Gosling.
The following segment of code accordingly, will not be compiled and an
compile-time error will be issued by the compiler, if an attempt is
made to compile it.
Because it violates the rule you just described.
final keyword simply means "this cannot be changed".It can be used with both fields and variables in a method.When a variable is declared final an attempt to change the variable will result to a compile-time error.For example if i declare a variable as final int x = 12; trying to increment x that is (++x) will produce an error.In short with primitives final makes a value a constant.
On the other hand static can only be applied with fields but not in methods.A field that is final static has only one piece of storage.final shows that it is a constant(cannot be changed), static shows it is only one.
In Java, a static variable is one that belongs to class rather than the object of a class, different instances of the same class will contain the same static variable value.
A final variable is one that once after initialized ,after the instantiation of a class (creation of an object) cannot be altered in the program. However this differ from objects if a different value is passed post creation of another object of the same class.
final static means that the variable belongs to the class as well as cannot be change once initialized. So it will be accessible to the same value throughout different instances of the same class.
Just to add a minor information to #Bruno Reis 's answer, which I sought to complete the answer, as he spoke about important condition to initialize final fields before constructor ends, final static fields must also be initialized before before static blocks' execution finishes.
You cannot declare static fields in static block, static fields can only belong to a class, hence the compiler error.
A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere. But why should the same variable be declared as final, which will not allow the variable to be changed else where (constant value)?
static so that the variable or method can be accessed without creating a class instance, and there is only one variable for the class instead of one for each instance.
A final class cannot be extended. A final variable cannot have its value changed, it behaves as a constant. And a final method cannot be over-ridden.
The minute a variable is defined as final, it should probably not be referred to as "variable", since it no longer "varies" :)
A static variable is not tied to any particular instance of a class -- it is only tied to the class itself and only from a scoping standpoint.
So there you are -- a static and final variable is actually a value that is not tied to any particular instance of class and does not vary. It is a constant value, to be referenced from anywhere in your Java code.
At some point, when you should decide to change the value of this constant, it only takes one change to propagate this change correctly to all other classes that use this constant.
A variable declared as static means that its value is shared by all instances of this class. Declaring a variable as final gives a slightly better performance and makes your code better readable.
local variables are on the stack and are not static.
You can have a static field which may or may not be final. You would make the field final if it is not going to change.
static fields can be modified (e.g. public static fields can be modified by any class). static final fields cannot be modified after initialization.
Like you mention yourself, this is done to create constants. You create a single field to hold a value with a specific meaning. This way you don't have to declare that value everywhere, but instead you can reference the static.
Static has nothing to do with getting the latest and single copy unless "single copy" here means one and the same value for all the instances of a class (however, I think you may be confusing it with volatile). Static means class variable. You make it final when you want that to be a constant (that's actually the way Java constants are declared: static final).
static final is used in Java to express constants. Static is used to express class variables, so that there is no need to instantiate an object for that class in order to access that variable.
Final methods can't be overriden and final variables can only be initialised once.
If you only use the static keyword, that value will not be a constant as it can be initialised again.
May be to provide something similar to constants.
Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.
for example user.lastName lastName should be field because it is needed during object lifecycle
Variables should be declared as static only if they’re not required for use in more than one method of the class or if the program should not save their values between calls to the class’s methods.
for example Math.max(num1,num2) Im not intristed in num1 and num2 after compleating this operation
Final stops any classes inheriting from it
You create static final variable to make its value accessible without instantiating an object.
E.G.:
public class MyClass
{
public static final String endpoint= "http://localhost:8080/myClass":
/* ...*/
}
Then you can access to the data using this line:
MyClass.endpoint
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.
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.
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.
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.
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.
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.
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.