A method can return any type of data, including objects.
// Returning an object. class Test {// w w w . j ava 2 s . c om int a; Test(int i) { a = i; } Test createNew() { Test temp = new Test(a+10); return temp; } } public class Main { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.createNew(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.createNew(); System.out.println("ob2.a after second increase: " + ob2.a); } }
createNew()
returns a new object each time it is being called.