【问题标题】:What is the use of final, while declaring the String variable?声明 String 变量时,final 的用途是什么?
【发布时间】:2018-02-11 11:24:34
【问题描述】:

我的编译器在声明 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 而不是string,您的代码运行良好并且没有final
  • 这段代码应该没有问题,除非您在内部创建匿名类时访问该字符串。也是字符串不是字符串。
  • 请遵守命名约定(类名以大写开头)(outerclass,a,b),因为如果满足假设,它会使代码的阅读更容易。我希望您的意思是字符串,而不是字符串 - 否则您必须更正该行。

标签: java class static


【解决方案1】:

final 可用于类、方法和变量。如果在类上使用,则意味着您不能对其进行子类化。例如,String 是 final 类,这意味着您不能使用自己的类对其进行扩展。

在方法上使用时,表示该方法不能在子类中被覆盖。如果您想确保没有人使用您的代码会更改您的方法的实现,这可能很有用。

在变量上,它有点复杂。当你将一个变量设为 final 时,这意味着你要么必须在 decleration 期间给它一个值:

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-correctness,其中 const 对象实际上具有不同的类型。

【讨论】:

  • 您不必在构造函数中设置它。您可以在初始化程序中设置它。
  • 这就是我写的。
  • 您写道“当您将变量设为 final 时,这意味着您要么必须在 decleration 期间给它一个值……要么在构造函数中”。您也可以在初始化程序中执行此操作:final String dogSound; { dogSound = "woof"; }.
猜你喜欢
  • 2010-12-13
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 2021-12-16
相关资源
最近更新 更多