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?
A constructor should have the name same as the class. Since anonymous inner class has no name, an anonymous inner class cannot have an explicit constructor in Java.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
During construction, there might exist exactly one instance of an anonymous class. Therefore, they can never be abstract. Since they have no name, we can't extend them. For the same reason, anonymous classes cannot have explicitly declared constructors.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With