“最终阶级”的重点是什么?在Java? [英] What is the point of "final class" in Java?

查看:129
本文介绍了“最终阶级”的重点是什么?在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本关于Java的书,它说你可以将整个班级声明为 final 。我想不出任何我使用它的地方。

I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this.

我只是编程的新手,我想知道程序员是否真的在他们的程序中使用它。如果他们这样做,他们何时使用它,以便我能更好地理解它并知道何时使用它。

I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it.

如果Java是面向对象的,并且你声明了一个类 final ,那么它是否会阻止类的想法具有对象的特征?

If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?

推荐答案


如果有,他们什么时候使用它所以我可以更好地理解它并知道何时使用它。

A final class只是一个无法扩展的类。

A final class is simply a class that can't be extended.

(这并不意味着对所有对象的引用该类的行为就好像它们被声明为 final 。)

(This does not mean that all references to objects of the class would act as if they were declared as final.)

当一个类声明为最终类时很有用在这个问题的答案中涵盖:

When it's useful to declare a class as final is covered in the answers of this question:

  • Good reasons to prohibit inheritance in Java?

如果Java是面向对象的,那么你声明了ac lass final ,是不是会停止具有对象特征的类的想法?

If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?

在某种意义上是的。

通过将一个类标记为final,您可以为该部分代码禁用该语言的强大而灵活的功能。但是,某些类不应该(并且在某些情况下可以不是)设计为以良好的方式考虑子类。在这些情况下,将类标记为final是有意义的,即使它限制了OOP。 (请记住,最终的课程仍然可以延长另一个非最终课程。)

By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)

相关文章: Java:何时创建最终类

这篇关于“最终阶级”的重点是什么?在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆