为什么从类构造函数调用的方法应该是最终的? [英] Why should methods called from a class constructor be final?

查看:62
本文介绍了为什么从类构造函数调用的方法应该是最终的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java新手,我试图从Oracle网站上的教程中理解以下内容:

I'm a Java novice and I was trying to make sense of the following line from the tutorial at the Oracle website: https://docs.oracle.com/javase/tutorial/java/IandI/final.html

从构造函数调用的方法通常应声明为final.如果构造函数调用非最终方法,则子类可能会重新定义该方法,从而产生令人惊讶或不良的结果.

Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.

我试图多次阅读它,以弄清子类如何重新定义从构造函数调用的方法.我是否应该假设构造函数正在调用的方法是在构造函数的类中声明的方法?如果从构造函数内部调用方法,为什么还要将其声明为final?(而不是从嵌套类或其他方法中来?)我无法绕过该语句.一个例子将是很好的.

I tried reading it multiple times trying to make sense of how a method called from a constructor can be redefined by a subclass. Should I assume the method being called by the constructor is one declared within the class of the constructor? And why should a method be declared final if it's called from within a constructor? (As opposed to from within a nested class or within another method?) I wasn't able to wrap my head around that statement. An example would be great.

推荐答案

这是有效的代码(编译):

This is valid code (compiles):

class Person {
    Person() {
        init();
    }

    void init() {
        // do stuff
    }
}

class Employee extends Person {
    Employee() {
        super();
    }

    void init() {
        // do something else
    }
}

这是高度可疑的.因为 Person.init 可能对类的完整性起关键作用,并且不能保证 Employee.init 也会这样做.

And it's highly suspicious. Because Person.init might do something critical for the integrity of the class, and there's no guarantees that Employee.init will do it too.

仅将 Person.init 限制为 private 是不够的. Employee.init 仍然有效,但是会 shadow Person.init ,这很容易引起误解.最好设置 Person.init final ,以禁止创建 Employee.init .

Restricting Person.init to private is not good enough. Employee.init remains valid, but it will shadow Person.init, which will be simply very misleading. It's best to make Person.init final, which make prohibit creating Employee.init.

这篇关于为什么从类构造函数调用的方法应该是最终的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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