Java-Returning Objects

Returning Objects

A method can return any type of data, including class types that you create. For example, in the following program, the createData( ) method returns an object of Data.

Program

tgfgfg

Program Source

class Data {
    
    int data1;
    int data2;
}

class CreateData {
    
    Data createData()
    {
        return new Data();
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        CreateData cd = new CreateData();
        Data d1 = cd.createData();
        
        d1.data1 = 10;
        d1.data2 = 20;
        System.out.println("d1.data1 : "+d1.data1);
        System.out.println("d1.data2 : "+d1.data2);
    }
}

Leave a Comment