final static var
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Wednesday, May 7, 2003 11:06 PM

hi there;


as i understand, if we declared the variable static, this variable will share among the class without have a copy of its.


if we declared a final variable, it will prevent from changing the value.


what is definition if i declared a variable as
final static int/String ?


thanks in advance!

Re: final static var

Posted By:   David_Bates  
Posted On:   Thursday, May 8, 2003 03:12 AM

(Please see my post about ordering, it's a little lost among the posts).


One thing to consider about the 'final' modifier. It does not mean "the value cannot be changed". What it means is "the variable may not be re-assigned". For example:

public class OrderCount {
private int count;

public void incrementCount() {
this.count++;
}
}

public class Order {
public static final OrderCount totalNumberOfOrders = new OrderCount(0);
...
public void processOrder() {
// totalNumberOfOrders contains '0'
totalNumberOfOrders.incrementCount();
// totalNumberOfOrders contains '1'
}
}

This example is a little contrived, but the point about 'final' is still valid - the object may be "changed", but it just can't be "re-assigned".



This point shouldn't concern you when dealing with primitives or immutable objects (such as String), but you should be careful with more complex objects.

Re: final static var

Posted By:   Anonymous  
Posted On:   Thursday, May 8, 2003 12:10 AM

Hi Tan,


final static String str = "my value cannot be changed";


it means that a single copy of the variable is used by all objects and the value of this variable cannot be changed.

About | Sitemap | Contact