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

折月煮酒 提交于 2019-11-28 08:08:36
Bohemian

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
}

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.
}

In Java, you need to have a constructor no matter what. It can be as simple as

    public AnonymousConstructor()
    {
    }

Also there is no }; in java, simply dont put that semicolon. Also you always want to use access modifiers ie "public, private, or protected". Now you should be able to call the super consuctor.

For the main class, it is static and thus does not need a constuctor. If you want to make a method in the main class it must be static.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!