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

前端 未结 3 1762
萌比男神i
萌比男神i 2020-12-09 02:42

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 ne

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 03:20

    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
    }
    

提交回复
热议问题