在java中的超级调用之前创建一个对象 [英] create an object before the super call in java

查看:129
本文介绍了在java中的超级调用之前创建一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到那些不起作用的简单java代码:

 公共类Bar扩展AbstractBar {

私人决赛Foo foo = new Foo(bar);

public Bar(){
super(foo);
}
}

我需要在<$ c之前创建一个对象$ c> super()调用因为我需要在母类中推送它。



我不想使用初始化块而且我不想在我的构造函数中执行以下操作:



super(new Foo(bar)) ..



如何在超级电话会议之前将数据发送到母班?

解决方案

如果 Foo 必须存储在一个字段中,你可以这样做:

 公共类Bar扩展AbstractBar {
private final Foo foo;

私人酒吧(Foo foo){
super(foo);
this.foo = foo;
}

public Bar(){
this(new Foo(bar));
}
}

否则 super(新Foo) (bar))对我来说看起来很合法,你可以将 new Foo(bar)包装成 static 方法。



另请注意,字段初始值设定项(如示例中所示)和初始化程序块也无济于事,因为它们在超类之后运行构造函数。如果字段声明为 final ,则您的示例将无法编译,否则您将在超类构造函数中获得 null 。 / p>

Considering that simple java code which would not work:

public class Bar extends AbstractBar{

    private final Foo foo = new Foo(bar);

    public Bar(){
        super(foo);
    }
}

I need to create an object before the super() call because I need to push it in the mother class.

I don't want to use an initialization block and I don't want to do something like:

super(new Foo(bar)) in my constructor..

How can I send data to a mother class before the super call ?

解决方案

If Foo has to be stored in a field, you can do this:

public class Bar extends AbstractBar{    
    private final Foo foo;

    private Bar(Foo foo) {
        super(foo);
        this.foo = foo;
    }

    public Bar(){
        this(new Foo(bar));
    }
}

Otherwise super(new Foo(bar)) looks pretty legal for me, you can wrap new Foo(bar) into a static method if you want.

Also note that field initializers (as in your example) and initializer blocks won't help either, because they run after the superclass constructor. If field is declared as final your example won't compile, otherwise you'll get null in superclass constructor.

这篇关于在java中的超级调用之前创建一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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