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

前端 未结 3 1760
萌比男神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:09

    Every class (without a specific constructor) has a no-arg constructor by default. An empty constructor will be inserted and javac will place a super() call.

    In your current example, you could say

    new MyBob() {
      // anonymous MyBob sub-class 1, uses No arg constructor.
    }
    new MyBob("test") {
      // anonymous MyBob sub-class 2, uses Arg constructor.
    }
    

    or

    new MyBob("test", "ing") {
      // anonymous MyBob sub-class 3, uses 2 arg constructor.
    }
    

提交回复
热议问题