// No initialization when is declared
private final int number;
public MyClass(int n) {
// The variable can be assigned in the constructor, but then
// not modified later.
number = n;
}
public class StaticVariable
{
static int noOfInstances;
StaticVariable()
{
noOfInstances++;
}
public static void main(String[] args)
{
StaticVariable sv1 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
StaticVariable sv2 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
System.out.println("No. of instances for st2 : " + sv2.noOfInstances);
StaticVariable sv3 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);
System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);
}
}
程序输出如下:
正如我们在这个例子中看到的,每个对象都有自己的类变量副本。
C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 : 2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3
class A
{
final int f;
static final int sf = 5;
A(int num)
{
this.f = num;
}
void show()
{
System.out.printf("About Object: %s\n Final: %d\n Static Final: %d\n\n", this.toString(), this.f, sf);
}
public static void main(String[] args)
{
A ob1 = new A(14);
ob1.show();
A ob2 = new A(21);
ob2.show();
}
}
class Test{
public final int a;
}
Test t1 = new Test();
t1.a = 10;
Test t2 = new Test();
t2.a = 20; //fixed
因此,每个实例都有不同的字段一个的值。
对于静态最终,所有实例共享相同的值,并且在第一次初始化后不能更改。
class TestStatic{
public static final int a = 0;
}
TestStatic t1 = new TestStatic();
t1.a = 10; // ERROR, CAN'T BE ALTERED AFTER THE FIRST
TestStatic t2 = new TestStatic();
t1.a = 20; // ERROR, CAN'T BE ALTERED AFTER THE FIRST INITIALIZATION.
public class ConstTest
{
private final int value = 10;
private static final int valueStatic = 20;
private final File valueObject = new File("");
private static final File valueObjectStatic = new File("");
public void printAddresses() {
System.out.println("final int address " +
ObjectUtils.identityToString(value));
System.out.println("final static int address " +
ObjectUtils.identityToString(valueStatic));
System.out.println("final file address " +
ObjectUtils.identityToString(valueObject));
System.out.println("final static file address " +
ObjectUtils.identityToString(valueObjectStatic));
}
public static void main(final String args[]) {
final ConstTest firstObj = new ConstTest();
final ConstTest sndObj = new ConstTest();
firstObj.printAdresses();
sndObj.printAdresses();
}
}
第一个对象的结果:
final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@6c22c95b
final static file address java.io.File@5fd1acd3
第二个对象的结果:
final int address java.lang.Integer@6d9efb05
final static int address java.lang.Integer@60723d7c
final file address java.io.File@3ea981ca
final static file address java.io.File@5fd1acd3
public class LengthDemo {
public static void main(String[] args) {
Rectangle box = new Rectangle();
System.out.println("Sending the value 10.0 "
+ "to the setLength method.");
box.setLength(10.0);
System.out.println("Done.");
}
}
public class ExperimentFinal {
private final int a;
private static final int b = 999;
public ExperimentFinal(int a) {
super();
this.a = a;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void print(int a, int b) {
System.out.println("final int: " + a + " \nstatic final int: " + b);
}
public static void main(String[] args) {
ExperimentFinal test = new ExperimentFinal(9);
test.print(test.getA(), test.getB());
} }
正如你可以看到上面的例子,对于“final int”,我们可以为类的每个实例(对象)分配变量,然而对于“static final int”,我们应该在类中分配一个变量(静态变量属于类)。
final String CENT_1 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
final static String CENT_2 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
例子:
package test;
public class Test {
final long OBJECT_ID = new Random().nextLong();
final static long CLASSS_ID = new Random().nextLong();
public static void main(String[] args) {
Test[] test = new Test[5];
for (int i = 0; i < test.length; i++){
test[i] = new Test();
System.out.println("Class id: "+test[i].CLASSS_ID);//<- Always the same value
System.out.println("Object id: "+test[i].OBJECT_ID);//<- Always different
}
}
}
public final class Foo
{
private final int i;
private static final int j=20;
public Foo(int val){
this.i=val;
}
public static void main(String[] args) {
Foo foo1= new Foo(10);
Foo foo2= new Foo(40);
System.out.println(foo1.i);
System.out.println(foo2.i);
System.out.println(check.j);
}
}
public class City {
// base price that is always same for all objects[For all cities].
private static double iphone_base_price = 10000;
// this is total price = iphone_base_price+iphone_diff;
private double iphone_citi_price;
// extra price added to iphone_base_price. It is constant per city. Every
// city has its own difference defined,
private final double iphone_diff;
private String cityName = "";
// static final will be accessible everywhere within the class but cant be
// changed once initialized.
private static final String countryName = "India";
public City(String cityName, double iphone_diff) {
super();
this.iphone_diff = iphone_diff;
iphone_citi_price = iphone_base_price + iphone_diff;
this.cityName = cityName;
}
/**
* get phone price
*
* @return
*/
private double getPrice() {
return iphone_citi_price;
}
/**
* Get city name
*
* @return
*/
private String getCityName() {
return cityName;
}
public static void main(String[] args) {
// 300 is the
City newyork = new City("Newyork", 300);
System.out.println(newyork.getPrice() + " " + newyork.getCityName());
City california = new City("California", 800);
System.out.println(california.getPrice() + " " + california.getCityName());
// We cant write below statement as a final variable can not be
// reassigned
// california.iphone_diff=1000; //************************
// base price is defined for a class and not per instances.
// For any number of object creation, static variable's value would be the same
// for all instances until and unless changed.
// Also it is accessible anywhere inside a class.
iphone_base_price = 9000;
City delhi = new City("delhi", 400);
System.out.println(delhi.getPrice() + " " + delhi.getCityName());
City moscow = new City("delhi", 500);
System.out.println(moscow.getPrice() + " " + moscow.getCityName());
// Here countryName is accessible as it is static but we can not change it as it is final as well.
//Something are meant to be accessible with no permission to modify it.
//Try un-commenting below statements
System.out.println(countryName);
// countryName="INDIA";
// System.out.println(countryName);
}
}