实例变量在Java中为final

实例变量: 众所周知,当变量的值因对象而异时,这种类型的变量称为实例变量。实例变量在类中声明,但不在任何方法、构造函数、块等中声明。如果不初始化实例变量,则JVM会根据该实例变量的数据类型自动提供默认值。 但是如果我们将一个实例变量声明为 最终的 ,那么我们必须注意实例变量的行为。

null
  • 因此,不要求将变量设置为最终变量。然而,如果确实明确表示永远不会更改变量,那么最好将其设置为最终变量
  • 在创建过程中,我们必须使用实例变量作为最终变量 不变的类。

有关最终实例变量的要点:

  1. 必须初始化变量: 如果实例变量声明为final,那么无论是否使用它,我们都必须显式地执行初始化,JVM不会为final实例变量提供任何默认值。

    // Java program to illustrate the behavior
    // of final instance variable
    class Test {
    final int x;
    public static void main(String[] args)
    {
    Test t = new Test();
    System.out.println(t.x);
    }
    }

    
    

    输出:

    error: variable x not initialized in the default constructor
    
  2. 构造函数完成前的初始化: 对于最终实例变量,我们必须在构造函数完成之前执行初始化。我们可以在声明时初始化一个最终实例变量。

    // Java program to illustrate that
    // final instance variable
    // should be declared at the
    // time of declaration
    class Test {
    final int x = 10 ;
    public static void main(String[] args)
    {
    Test t = new Test();
    System.out.println(t.x);
    }
    }

    
    

    输出:

    10
    
  3. 在非静态块或实例块内初始化: 我们还可以在非静态或实例块中初始化最终实例变量。

    // Java program to illustrate
    // that final instance variable
    // can be initialize within instance block
    class Test {
    final int x;
    {
    x = 10 ;
    }
    public static void main(String[] args)
    {
    Test t = new Test();
    System.out.println(t.x);
    }
    }

    
    

    输出:

    10
    
  4. 默认构造函数中的初始化: 在默认构造函数中,我们还可以初始化一个最终实例变量。

    // Java program to illustrate that
    // final instance variable
    // can be initialized
    // in the default constructor
    class Test {
    final int x;
    Test()
    {
    x = 10 ;
    }
    public static void main(String[] args)
    {
    Test t = new Test();
    System.out.println(t.x);
    }
    }

    
    

    输出:

    10
    

上面提到的是对最终实例变量执行初始化的唯一可能位置。如果我们尝试在其他任何地方执行初始化,那么我们将得到编译时错误。

// Java program to illustrate
// that we cant declare
// final instance variable
// within any static blocks
class Test {
final int x;
public static void main(String[] args)
{
x = 10 ;
Test t = new Test();
System.out.println(t.x);
}
}


输出:

error: non-static variable x cannot be referenced from a static context

// Java program to illustrate that we
//  cant declare or initialize
// final instance variable within any methods
class Test {
final int x;
public void m()
{
x = 10 ;
}
}


输出:

error: cannot assign a value to final variable x

本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享