Is final String s = “Hello World” same as String s

2019-02-23 18:25发布

If a class is defined as final and we declare an instance of the final class... Would it make any difference? or is final in such cases would be redundant?

final String s = "Hello World" 

same as

String s = "Hello World"

3条回答
做自己的国王
2楼-- · 2019-02-23 18:40

When you use final on the variable, it means that it cannot be re-assigned. Consider the following example:

public class FinalExample {
    private final String a = "Hello World!"; // cannot be reassigned
    private String b = "Goodbye World!"; // can be reassigned

    public FinalExample() {
        a = b; // ILLEGAL: this field cannot be re-assigned
        b = a; 
    }

    public static void main(String[] args) {
        new FinalExample();
    }
}

If you try to run it, you will get an error on a=b:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The final field FinalExample.a cannot be assigned

    at FinalExample.<init>(FinalExample.java:7)
    at FinalExample.main(FinalExample.java:12)

Now, I think you were wondering whether it matters to have a final or not in front of the String data type specifically. Although you may have heard that String is immutable, you can still re-assign something like String s = "Hello World!"; to another string value. This distinction is due to the fact that you are actually re-assigning the reference of String s to a new string. Therefore, the following is valid:

String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);

Output: Goodbye World!

But you can use the final declaration to prevent this change:

final String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);

Output: 
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The final local variable s cannot be assigned. It must be blank and not using a compound assignment

The final declaration is great to use if you want to ensure that no one can change your String reference. You can use final for other data types as well to prevent the reference from being changed.

查看更多
聊天终结者
3楼-- · 2019-02-23 18:44

final on a variable has nothing to do with whether the class is final.

final String s = "Hello World";
s = "Goodbye";  // illegal

String s2 = "Hello World";
s2 = "Goodbye";  // legal
查看更多
相关推荐>>
4楼-- · 2019-02-23 19:05

A final variable cannot be bound to another instance, so this is not valid:

final String s = "123";
s = "234"; // doesn't work!

A final class cannot be extended

final class A {
}

class B extends A { // does not work!
}

And both of this is not to be confused with immutable classes (like String). Instances of immutable classes won't change their state. (There is no direct language support for immutable classes, but in practice most of the time all attributes of immutable classes are declared final.)

查看更多
登录 后发表回答