Is there something equivalent for StaticClass::new
for inner class given the outer class instance?
Edit:
I.e. if I have
class Outer {
class Inner {
}
}
I can do Outer o = new Outer(); Inner i = o.new Inner()
in old Java. How can I express the o.new Inner()
as function reference.
Anonymous inner class always extend a class or implement an interface. Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
You can declare fields and methods inside an anonymous class, but you cannot declare a constructor. You can declare a static initializer for the anonymous class instead, though.
You can only make nested classes either static or non-static. If you make a nested class non-static then it also referred to as Inner class.
According to the Oracle tutorials, there are four kinds of method references:
ContainingClass::staticMethodName
containingObject::instanceMethodName
ContainingType::methodName
ClassName::new
References to a local/nested class are not listed, so I would assume it's not supported.
You can use the java.util.function.Supplier
to trigger the usage of lambdas in order to obtain an instance of the nested class:
Outer outer = new Outer();
Supplier<Outer.Inner> supplier = () -> outer.new Inner();
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