Constructor Reference for Array

Java-Constructor Reference for Arrays

Constructor Reference for Arrays

Another form of the constructor reference syntax that is used for arrays. To create a constructor reference for an array, use the construct : type[ ]::new. Type specifies the type of object being created. For example, the following creates a three-element array of MyClass objects and gives each element an initial value. The call to myMethod(3) causes a three-element array to be created. In general, a functional interface must contain a method that takes a single int parameter if it is to be used to refer to an array constructor.

Program

Constructor Reference for Array

Program Source

interface MyInterface {

    MyClass[] myMethod(int num);
}

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[] myCarray = myi.myMethod(3);
        myCarray[0] = new MyClass(15);
        myCarray[1] = new MyClass(30);
        myCarray[2] = new MyClass(45);
        myCarray[0].showData();
        myCarray[1].showData();
        myCarray[2].showData();
    }
}

Leave a Comment