使用final方法初始化实例变量 [英] Using final methods to initialize an instance variable

查看:107
本文介绍了使用final方法初始化实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Sun文档


通常,你会将代码放到
初始化
构造函数中的实例变量。
有两个
使用构造函数替代
初始化实例变量:
初始化块和最终方法。

Normally, you would put code to initialize an instance variable in a constructor.
There are two alternatives to using a constructor to initialize instance variables: initialize blocks and final methods.

我可以了解初始化块的使用。任何人都可以解释使用最终方法进行var初始化吗?非最终的公共制定者可以完成这项工作。为什么不直接使用它们?

I could understand the use of initialize blocks. Can anyone please explain the use of final methods for instance var initialization? A non-final public setter can do this job. Why not just use them ?

推荐答案

这个优点已在您链接到的Sun教程中描述:

The advantage is already described in the very same Sun tutorial you linked to:


无法在子类中重写最终方法。这将在有关接口和继承的课程中讨论。

A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance.

如果子类可能想重用初始化方法,这尤其有用。该方法是最终的,因为在实例初始化期间调用非final方法可能会导致问题。 Joshua Bloch在 Effective Java(第17项设计和继承文档)中更详细地描述了这一点。 。

This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems. Joshua Bloch describes this in more detail in Effective Java(item 17 Design and document for inheritance).

非最终方法在初始化中存在危险的原因是因为超类的实例初始化在初始化子类之前执行。因此,如果非最终方法在子类中被覆盖并且在超类的初始化期间执行,则它可能正在访问子类的未初始化字段,从而产生错误结果。

The reason a non-final method is dangerous in initialization is because the instance initialization of the superclass executes before the sub class is initialized. Therefore if the non-final method is overriden in the sub class and is executed during the initialization of the superclass it may be accessing uninitialized fields of the subclass giving erroneous results.

一般规则是(引用Effective Java):构造函数不得直接或间接调用可覆盖的方法。

The general rule is(quoting from Effective Java): Constructors must not invoke overridable methods, directly or indirectly.

这篇关于使用final方法初始化实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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