第一章java中的final关键字与示例


在这篇文章中,我们将看到java中的 final 关键字。最终关键字可以与:

  • variable
  • method
  • class

当您想要限制其他人进行任何更改时,通常会使用 Final。

让我们一个一个来看看。


最终变量

如果您将任何变量设为最终变量,则以后不允许更改其值。它将是常量。如果您尝试更改值,则编译器会给您错误。

我们举一个简单的例子:

package org.arpit.java2blog;

public class FinalExample{

    final int count=10;

    public void setCount()
    {
        count=20;
    }
}

在上面的示例中,您将在突出显示的行中收到带有文本“无法分配最终字段 FinalExampleMain.count”的编译错误。

空白最终变量

空白最终变量是在声明时未初始化的变量。它只能在构造函数中初始化。

但是如果你不初始化最终变量,你会得到如下编译错误。

package org.arpit.java2blog;

public class FinalExample {

    final int count;

}

在上面的示例中,您将在突出显示的行中收到带有文本“空白最终字段计数可能尚未初始化”的编译错误。 您可以在构造函数中初始化最终变量一次,如下所示。

package org.arpit.java2blog;

public class FinalExample {

    final int count;

    FinalExample(int count)
    {
        this.count=count;
    }   
        public static void main(String args[])
    {
        FinalExample fe=new FinalExample(10);
        System.out.println(fe.count);   
    }
}

上面的代码可以正常工作。你可能在想它有什么用。 假设您有 Employee 类,它有一个名为 empNo 的属性。一旦创建了对象,您就不想更改 empNo。 因此,您可以将其声明为 final 并在构造函数中对其进行初始化。

静态空白最终变量

静态空白最终变量是在声明时未初始化的静态变量。它只能在静态块中初始化。

package org.arpit.java2blog;

public class FinalExample {

    static final int count;

    static   
    {
             count=10; 
    }   
    public static void main(String args[])
    {
         System.out.println(FinalExample.count);    
    }
}

当你运行上面的程序时,你会得到下面的输出:

10

最终方法

您不能覆盖子类中的最终方法。您可以使用子类的对象调用父类的最终方法,但不能覆盖它。

package org.arpit.java2blog;

public class Shape{

    public final void draw()
    {
        System.out.println("Draw method in shape class");
    }
}

class Rectangle extends Shape
{
    public void draw()
    {
        System.out.println("Draw method in shape class");
    }

    public static void main(String args[])
    {
        Rectangle rectangle= new Rectangle();
        rectangle.draw();
    }
}

如果从 rectangle 类中删除 draw 方法,它将正常工作。

package org.arpit.java2blog;

public class Shape{

    public final void draw()
    {
        System.out.println("Draw method in shape class");
    }
}

class Rectangle extends Shape
{
    public static void main(String args[])
    {
        Rectangle rectangle= new Rectangle();
        rectangle.draw();
    }
}

当你运行上面的程序时,你会得到下面的输出:

Draw method in shape class

如果您声明一个类 final,则没有其他类可以扩展它。

package org.arpit.java2blog;

final class Shape{

    public final void draw()
    {
        System.out.println("Draw method in shape class");
    }
}

class Rectangle extends Shape
{   
    public static void main(String args[])
    {
        Rectangle rectangle= new Rectangle();
        rectangle.draw();
    }
}

您将在带有文本“The type Rectangle cannot subclass the final class Shape”的突出显示行处获得编译错误。


原文链接:https://codingdict.com/