A method can return an object in a similar manner as that of returning a variable of primitive types from methods. When a method returns an object, the return type of the method is the name of the class to which the object belongs and the normal return statement in the method is used to return the object. This can be illustrated in the following program.
//Add two times and display information in proper time format
class Time
{
private int hours, mins,secs;
Time() //Constructor with no parameter
{
hours = mins = secs = 0;
}
Time(int hh, int m, int ss) //Constructor with 3 parameters
{
hours = hh;
mins = m;
secs = ss;
}
Time add(Time tt2)
{
Time Temp = new Time();
Temp.secs = secs + tt2.secs ; //add seconds
Temp.mins = mins + tt2.mins; //add minutes
Temp.hours = hours + tt2.hours; //add hours
if(Temp.secs > 59) //seconds overflow check
{
Temp.secs = Temp.secs - 60; //adjustment of minutes
Temp.hours++; //carry hour
}
return Temp;
}
void display()
{
System.out.println(hours + " : "+ mins +" : "+ secs);
}
}
class ReturningObjectsfromMethods
{
public static void main(String[] args)
{
Time t1 = new Time(4,58,55);
Time t2 = new Time(3,20,10);
Time t3;
t3 = t1.add(t2);
System.out.print("Time after addition (hh:min:ss) ---->");
t3.display();
}
}
The above program is used to add two times and display the result in proper time format. We begin by taking a class Time that consists of private data members hours, mins, sees and public methods add () and display (). The objects t1 and t2 are instantiated and their fields are assigned values by invoking the constructor.
The statement,
t3 = t1.add(t2);
invokes the add () method using the object t1 and pass the object t2 as an argument by value. In the add () method, the data members of object t1 can be accessed simply by their name whereas the data members of object t2 can be accessed by its copy t t2 using a dot operator. A local object temp is instantiated that stores the result of addition of two given time.
The object temp is finally returned to object t3 in main () using the return statement. The result is displayed using the statement,
t3.display ();