Thursday, January 21, 2016

Topic 16: Methods returning class object

A method can return any type of data, including class types that we create. For ex, consider the code fragment:

// Inside class Test
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;

}

//Inside class containing main()
Test ob1 = new Test(2);
Test ob2 = ob1.incrByTen();

System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);

Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

Each time incrByTen( ) is invoked, a new object is created. Reference is returned to the calling routine.


Click for NEXT article.


Please feel free to correct me by commenting your suggestions and feedback.


No comments:

Post a Comment