简体   繁体   中英

Why there Static Final variables in Test classes in java?

I have seen that most of the test classes have constants declared as final static, what the use of keeping them static? We can create constants by final keyword itself?Why to have final static in test classes?

private static final String var ="test";
private final String var ="test";

Why to prefer 1st choice over 2nd?

Your confusion is on Static and Non-static concepts let's follow the below code

public class StaticFinal {
    private static  String staticVariable = "Static Value";
    private String nonStaticVariable = "Non Static Value";

    public static void main(String[] args) {
        StaticFinal staticfinal_1 = new StaticFinal();
        StaticFinal staticfinal_2 = new StaticFinal();

        System.out.println(staticfinal_1.nonStaticVariable); //Out-Put: Non Static Value
        staticfinal_1.nonStaticVariable = "New Non Static Value"; //Changing non-Static 'nonStaticVariable' value on staticfinal_1 only
        System.out.println(staticfinal_1.nonStaticVariable); //Out-Put: New Non Static Value
        System.out.println(staticfinal_2.nonStaticVariable); //Out-Put: Non Static Value (remain unchanged)


        System.out.println(staticfinal_1.staticVariable); //Out-Put: Static Value
        staticfinal_1.staticVariable = "New Static Value"; //Changing Static 'staticVariable' value using staticfinal_1 object
        System.out.println(staticfinal_1.staticVariable); //Out-Put: New Static Value 
        System.out.println(staticfinal_2.staticVariable); //Out-Put: New Static Value 

    }
}

Output as follow

Non Static Value
New Non Static Value
Non Static Value
Static Value
New Static Value
New Static Value

A Static variable is shared by multiple objects of a class and static variables are properties of the class, that's why when staticfinal_1.staticVariable = "New Static Value"; is executed the result shows the same for both the objects.

System.out.println(staticfinal_1.staticVariable); //Out-Put: New Static Value 
System.out.println(staticfinal_2.staticVariable); //Out-Put: New Static Value 

And non-static variables are properties of class objects, which means when we create objects of a class a copy of non-static variable is created for each object, that's why when staticfinal_1.nonStaticVariable = "New Non Static Value"; is executed the result differs for both objects

System.out.println(staticfinal_1.nonStaticVariable); //Out-Put: New Non Static Value
System.out.println(staticfinal_2.nonStaticVariable); //Out-Put: Non Static Value (remain unchanged)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM