如何从匿名内部类调用特定的父构造函数? [英] How to call a specific parent constructor from anonymous inner class?

查看:171
本文介绍了如何从匿名内部类调用特定的父构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我知道一个匿名内部类是隐式地扩展父类或实现一个接口,因此超类的构造函数将需要被调用。但是,我不知道如何创建一个构造函数的匿名类(如果这是可能的),没有定义一个构造函数我不知道如何调用super()!这是我的练习代码:

Ok, So I know that an anonymous inner class is either implicitly extending a parent class or implementing an interface, and therefore a constructor of the superclass will need to be called. However, I'm not sure how to create a constructor for the anonymous class (if this is possible) and without defining a constructor I'm not sure how to make calls to super()! Here is my practice code:

public class AnonymousConstructor {
    public static void main(String[] args) {
        //I'm not sure how to explicitly call one of the arg super constructors
        MyBob my = new MyBob() {
            //I would like to do something like this super("String"); or      
            //super("String", "String");
        };

    }
}

class MyBob extends Thread {
    MyBob() {
        System.out.println("No arg constructor");
    }
    MyBob(String a) {
        System.out.println("Arg constructor");
    }
    MyBob(String a, String b) {
        System.out.println("2 arg constructor");
    }
    public void run() {
        System.out.println("Outer");
    }
}

我担心的是,如果你尝试匿名类从没有一个无arg的构造函数的代码将在编译时失败的类,因为没有办法传递参数到超构造函数。

My concern is that if you try to make an anonymous class from a class that doesn't have a no-arg constructor that the code will fail at compile time because there is no way to pass an argument to the superconstructor. Is this a valid concern, and if so, is there a way around this?

推荐答案

您不能为构造函数定义构造函数匿名类(部分),但您可以通过向 new 调用提供参数来控制调用哪个超级构造函数:

You can't define a constructor for an anonymous class (part of the language specification), but you can control which super constructor is called by simply providing arguments to the new call:

MyBob my = new MyBob("foo") { // super(String) is called
    // you can add fields, methods, instance blocks, etc, but not constructors
}

这篇关于如何从匿名内部类调用特定的父构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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