我正在读一本关于Java的书,它说你可以将整个类声明为final。我想不出有什么地方可以用它。

我只是一个编程新手,我想知道程序员是否真的在他们的程序中使用这个。如果他们使用,他们什么时候使用,这样我就能更好地理解它,知道什么时候使用它。

如果Java是面向对象的,并且你声明了一个final类,难道它不会阻止类具有对象的特征吗?


当前回答

其他的答案集中在final类告诉编译器什么:不允许另一个类声明它扩展了这个类,以及为什么这样做是可取的。

但是编译器并不是短语final类的唯一读者。每个读源代码的程序员也会读这个。它可以帮助快速理解程序。

In general, if a programmer sees Thing thing = that.someMethod(...); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing, they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it's base classes.

其他回答

Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."

我只知道一个实际用例:生成类

在生成类的用例中,我知道一个:依赖注入,例如https://github.com/google/dagger

假设你有一个Employee类,它有一个方法greet。当greet方法被调用时,它只是简单地打印Hello everyone!这就是greet方法的预期行为

public class Employee {

    void greet() {
        System.out.println("Hello everyone!");
    }
}

现在,让GrumpyEmployee继承Employee并重写greet方法,如下所示。

public class GrumpyEmployee extends Employee {

    @Override
    void greet() {
        System.out.println("Get lost!");
    }
}

现在在下面的代码中看看sayHello方法。它以Employee实例作为参数,并调用greet方法,希望它会说Hello everyone!但我们得到的是滚开!这种行为变化是因为员工grumpyEmployee = new grumpyEmployee ();

public class TestFinal {
    static Employee grumpyEmployee = new GrumpyEmployee();

    public static void main(String[] args) {
        TestFinal testFinal = new TestFinal();
        testFinal.sayHello(grumpyEmployee);
    }

    private void sayHello(Employee employee) {
        employee.greet(); //Here you would expect a warm greeting, but what you get is "Get lost!"
    }
}

如果Employee类是final类,则可以避免这种情况。想象一下,如果没有将String Class声明为final,厚脸皮的程序员会造成多大的混乱。

在java中,final关键字用于以下场合。

最后一个变量 最后的方法 最后的课程

在java中,final变量不能重赋,final类不能扩展,final方法不能重写。

Final类不能进一步扩展。如果不需要在java中使类可继承,可以使用这种方法。

如果我们只需要让一个类中的特定方法不被覆盖,我们可以把final关键字放在它们前面。在那里类仍然是可继承的。