Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

java - How to call a specific parent constructor from anonymous inner class?

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");
    }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...