Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor method reference for (non-static) inner class?

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.

like image 519
billc.cn Avatar asked Mar 11 '15 09:03

billc.cn


People also ask

Can we construct constructor inside inner class?

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.

How do you instantiate a non-static inner 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.

Are constructor Cannot be provided for which of the following inner classes?

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.

Can static inner class have non-static method?

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.


1 Answers

According to the Oracle tutorials, there are four kinds of method references:

  • Reference to a static method
    • ContainingClass::staticMethodName
  • Reference to an instance method of a particular object
    • containingObject::instanceMethodName
  • Reference to an instance method of an arbitrary object of a particular type
    • ContainingType::methodName
  • Reference to a constructor
    • 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();
like image 103
Konstantin Yovkov Avatar answered Oct 13 '22 01:10

Konstantin Yovkov