Constructor References

Java-Constructor References

Constructor References

It is also possible to create references to constructors. This is the general form of the syntax that you will use : className::new. This reference can be assigned to any functional interface reference that defines a method compatible with the constructor. For example, in the following program, the MyMethod( ) method of MyInterface returns a reference of type MyClass and has an int parameter.

Next, notice that MyClass define a constructor, that specifies a parameter of type int. The line : MyInterface myi = MyClass::new;  creates a constructor reference to a MyClass constructor. Because MyInterface’s MyMethod( ) method takes an int parameter, the constructor being referred to is MyClass(int da). Also notice that the reference to this constructor is assigned to a MyInterface reference called myi. After this statement executes, myi can be used to create an instance of MyClass, as the line MyClass myc = myi.MyMethod(50);. myi has become another way to call MyClass(int da).

Program

Constructor References

Program Source

interface MyInterface {

    MyClass MyMethod(int da);
}
class MyClass {
    
    private int data;
    
    MyClass(int da){
        
        data = da;
    }
    void showData(){
        
        System.out.println("data : "+data);
    }
}
public class Javaapp {
    
    public static void main(String[] args) {
        
        MyInterface myi = MyClass::new;
        MyClass myc = myi.MyMethod(50);
        myc.showData();
    }
}

Leave a Comment