![](/img/trans.png)
[英]What is the difference between declaring a String and declaring it as final?
[英]What is the use of final, while declaring the String variable?
我的编译器在声明 String 变量时显示错误,但提示显示 final 丢失。 更正后,它起作用了,但是final 有什么用?
class Outerclass
{
private static String upa = "tobby";
static class A
{
void printmessage(){
System.out.println("who is a good boy?"+upa);
}
}
class B
{
void printagain()
{
System.out.println("who is a bad boy?"+upa);
}
}
}
public class Main {
public static void main(String[] args) {
Outerclass.A oa=new Outerclass.A();
oa.printmessage();
Outerclass outer= new Outerclass();
outerclass.B ob= outer.new B();
ob.printagain();
}
}
final
可用于类、方法和变量。 如果在类上使用,则意味着您不能对其进行子类化。 例如, String
是一个 final 类,这意味着你不能用你自己的类来扩展它。
当在方法上使用时,这意味着该方法不能在子类中被覆盖。 如果您想确保没有人使用您的代码会更改您的方法的实现,这会很有用。
在变量上,它有点复杂。 当您将变量设为 final 时,这意味着您必须在声明期间给它一个值:
final String dogSound = "woof";
或在构造函数中:
final String dogSound;
public MyClass() {
dogSound = "woof";
}
在此之后,您不能分配新值,即使在构造函数中也不能。 编译器不会让你。
然而,这并不意味着最终的目标不能有它的内容改变。 鉴于此数组:
final String[] dogSounds = new String[1];
dogSounds[0] = "woof";
dogSounds[0] = "bark";
是完全合法的。
因此它不同于 C 和 C++ 中所谓的 const 正确性,其中const
对象实际上具有不同的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.