Java Programming | Function passing and returning object

Introduction

This is a tutorial for function passing and returning object in java. The program is given below that adds two complex numbers. The program is extendable. Go enjoy the program. Let begin…………

Before you begin.Do this

  1. Create a separate java file for other class.
  2. Create a java file for main class.
  3. Import the created java class in main class file.

Program for addition of two complex numbers using class in java.

1. Create a class.

//declare the package name if the class file is
//created in other package.
package Myclasses;
 
//import scanner
import java.util.Scanner;
 
//declare class
public class ComplexNo {
 
    //declare variables.
    private int a,b;
 
    //functions should be public if needed to access from other class
    public void getdata()
    {
        //print message to enter numbers
        System.out.println("Enter a and b of a+ib:");
        //Take input
        Scanner input = new Scanner(System.in);
        a = input.nextInt();
        b = input.nextInt();
    }
 
    public ComplexNo addit(ComplexNo x)
    {
        ComplexNo tmp = new ComplexNo();
        tmp.a = a+x.a;
        tmp.b = b+x.b;
        return tmp;
    }
 
    public void print()
    {
        System.out.println("The Sum of Complex Numbers = "+a+"+i"+b);
    }
}

2. Create ClassFunct.java file.

//import our class
import Myclasses.ComplexNo;
 
// the name of our class its public
public class ClassFunct {
    //void main
        public static void main (String[] args)
        {
            //declare class
            ComplexNo no1 = new ComplexNo();
            ComplexNo no2 = new ComplexNo();
            ComplexNo sum = new ComplexNo();
            //call functions
            no1.getdata();
            no2.getdata();
            sum = no1.addit(no2);
            sum.print();
        }
}

Output

Enter a and b of a+ib:
1
2
Enter a and b of a+ib:
1
3
The Sum of Complex Numbers = 2+i5

How it Works

  1. Objects of class are created.
  2. The getdata function is called from main class.
  3. The sum function is called from main class.
  4. The print function is called from main class.

Extending it

The program can be extended by using the concept in any program.

  • Remember this is a basic part of java which can be used in any program….

Explanation.

Your class

  1. Create class.
  2. Import the Scanner.
  3. Declare the class as public
  4. Declare variables.
  5. Create functions.

Main class

  1. Create other class
  2. Import your class.
  3. Declare the class as public.
  4. Add the void main function.
  5. Declare class.
  6. Declare objects.
  7. Call functions.

At the end.

You learnt creating the Java program for Function passing and returning object . So now enjoy the program.

Please comment on the post and share it.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: