在构造函数中使用setter方法:不好的做法? [英] Using setter methods in constructor: bad practice?

查看:57
本文介绍了在构造函数中使用setter方法:不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到这样的构造函数

I often see constructors like this

public class A {

   private int b;

   public A(int b) {
      setB(b);
   }

   public void setB(int b) {
      this.b = b;
   }
}

这是个好主意吗?我应该在构造函数中使用setter方法吗?如果我要重写子类中的构造方法或setter方法,这不是问题吗?

Is this a good idea? Should I use setter methods in the constructor? Isn't it a problem if I would override either the constructor or the setter methods in a sub class?

推荐答案

可能不是是个好主意.如果您不将该类设置为final,也不将setName(...)方法设置为私有或final,则其他人可以扩展您的类并覆盖setName(...)方法.您的构造函数(在您的基类中)将在扩展类中而不是您的实现中调用该方法.没有人知道该方法可以做什么.根据经验:构造函数不应调用可以被覆盖的方法.

It's probably not a good idea. If you don't make that class final and don't make the setName( ... ) method private or final someone else is able to extend your class and overrid the setName( ... ) method. Your constructor (in your base class) will call that method in the extending class instead of your implementation. Nobody knows what that method can do. As a rule of thumb: a constructor shouldn't call methods that can be overriden.

这篇关于在构造函数中使用setter方法:不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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