Java可重写的调用构造函数 [英] Java overridable call in constructor

查看:229
本文介绍了Java可重写的调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个糟糕的(安全)实践,从Java中的对象构造函数调用可覆盖的方法。但是,例如,如果构造函数必须初始化一些数据,调用相应的setter方法似乎是合理的,这样我就不会复制代码。设置器是公共的,不是最终的。有没有什么标准的方法来处理这个,就像声明私有setter方法,公共的调用?下面是一些代码:

I know it is a bad (security) practice to call overridable methods from an object constructor in Java. However, for example, if the constructor has to initialize some data, it seems reasonable to call the respective setter method so that I don't copy code. The setters are public and not final. Is there any standard way of dealing with this, like declaring private setter methods, that the public ones call? To illustrate, here is some code:

class A {
    private double x,y;
    private privateSetX(double x1) { x=x1; }
    private privateSetY(double y1) { y=y1; }
    public A() { privateSetX(0); privateSetY(0); }
    public setX(double x1) { privateSetX(x1); }
    public setY(double y1) { privateSetY(y1); }
};


推荐答案

为此,创建一个由构造函数和公共设置器调用的辅助私有setter方法。

If you really want to do this, create a secondary private setter method that is called by both the constructor and the public setter.

这篇关于Java可重写的调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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