是否可以在构造函数中的super()之前进行计算? [英] Is it possible to do computation before super() in the constructor?

查看:128
本文介绍了是否可以在构造函数中的super()之前进行计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有一个类Base,它有一个带有TextBox对象的参数构造函数作为它的参数。如果我有一个简单的类以下形式:

Given that I have a class Base that has a single argument constructor with a TextBox object as it's argument. If I have a class Simple of the following form:

public class Simple extends Base {
  public Simple(){
    TextBox t = new TextBox();
    super(t);
    //wouldn't it be nice if I could do things with t down here?
  }
}

我会收到一个错误,告诉我打电话给super必须是构造函数中的第一个调用。但奇怪的是,我可以这样做。

I will get a error telling me that the call to super must be the first call in a constructor. However, oddly enough, I can do this.

public class Simple extends Base {
  public Simple(){
    super(new TextBox());
  }
}

为什么这是有限的,但是第一个例子不是?我可以理解需要先设置子类,也许不允许在调用超级构造函数之前实例化对象变量。但是t显然是一个方法(局部)变量,为什么不允许呢?

Why is it that this is permited, but the first example is not? I can understand needing to setup the subclass first, and perhaps not allowing object variables to be instantiated before the super-constructor is called. But t is clearly a method (local) variable, so why not allow it?

有没有办法解决这个限制?是否有一种安全的方法可以将变量保存到您可能构建的内容之前调用super但是在您输入构造函数之后?或者,更一般地说,允许在实际调用super之前进行计算,但是在构造函数中?

Is there a way to get around this limitation? Is there a good and safe way to hold variables to things you might construct BEFORE calling super but AFTER you have entered the constructor? Or, more generically, allowing for computation to be done before super is actually called, but within the constructor?

谢谢。

推荐答案

是的,您的简单案例有一个解决方法。您可以创建一个私有构造函数,它将 TextBox 作为参数,并从您的公共构造函数中调用它。

Yes, there is a workaround for your simple case. You can create a private constructor that takes TextBox as an argument and call that from your public constructor.

public class Simple extends Base {
    private Simple(TextBox t) {
        super(t);
        // continue doing stuff with t here
    }

    public Simple() {
        this(new TextBox());
    }
}

对于更复杂的东西,你需要使用工厂或静态工厂方法。

For more complicated stuff, you need to use a factory or a static factory method.

这篇关于是否可以在构造函数中的super()之前进行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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