Method returning an object in Java


A method can return any type of object. For example, in the following program GetMarks() takes a parameter as the Main class Object and also returns Main class objects. The object's data type is Main.

Example 1

Program
public class Main 
{
  int _marks;
  void SetMarks(int marks)
  {
   this._marks=marks;
  }
  Main GetMarks(Main m1)
  {
   Main m2=new Main();
   m2._marks=m1._marks;
   return m2;
  }
  public static void main(String[] args) 
  {
    Main s1=new Main();
    s1.SetMarks(85);
    Main s2=new Main();
    Main s3=s2.GetMarks(s1);
    System.out.println("Marks "+s3._marks);
  }
}

Method returning an object in java

Example 2

Program
class Complex
{
 int _i,_j;
 public void SetIJ(int i,int j)
 {
  this._i=i;
  this._j=j;
 }
 public Complex ComplexAdd(Complex c1, Complex c2)
 {
  Complex c3=new Complex();
  c3._i=c1._i+c2._i;
  c3._j=c1._j+c2._j;
  return c3;
 }
}
public class Main 
{
  
  public static void main(String[] args) 
  {
    Complex obj1=new Complex();
    obj1.SetIJ(10,20);
    Complex obj2=new Complex();
    obj2.SetIJ(20,30);
    Complex obj3=new Complex();
    Complex obj4=obj3.ComplexAdd(obj1,obj2);
    System.out.println("_i = "+obj4._i);
    System.out.println("_j = "+obj4._j);
  }
}

Method returning an object in java