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

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

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


当前回答

将一个类保留为最终类的一个好处是:-

String类保持为final,这样任何人都不能重写其方法并更改功能。例如,没有人可以改变length()方法的功能。它总是返回一个字符串的长度。

这个类的开发人员不希望任何人改变这个类的功能,所以他把它作为最终的。

其他回答

其他的答案集中在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.

是的,有时您可能需要这样做,无论是出于安全性还是速度原因。在c++中也可以做到。它可能不适用于程序,但更适用于框架。 http://www.glenmccl.com/perfj_025.htm

要解决最后一个类问题:

有两种方法可以让一门课成为期末考试。第一种是在类声明中使用关键字final:

public final class SomeClass {
  //  . . . Class contents
}

使类成为final的第二种方法是将其所有构造函数声明为private:

public class SomeClass {
  public final static SOME_INSTANCE = new SomeClass(5);
  private SomeClass(final int value) {
  }

如果您发现它实际上是final,那么将它标记为final可以省去麻烦,请查看这个Test类。乍一看是公开的。

public class Test{
  private Test(Class beanClass, Class stopClass, int flags)
    throws Exception{
    //  . . . snip . . . 
  }
}

不幸的是,由于类的唯一构造函数是private的,因此不可能扩展这个类。在Test类的情况下,没有理由该类应该是final类。Test类是隐式final类如何导致问题的一个很好的例子。

所以当你隐式地将一个类的构造函数设为private时,你应该将它标记为final。

假设你有一个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,厚脸皮的程序员会造成多大的混乱。

Android Looper类就是一个很好的例子。 http://developer.android.com/reference/android/os/Looper.html

Looper类提供了某些不打算被任何其他类覆盖的功能。因此,这里没有子类。