Methods

Overloading Methods

Java allows us to use same name of one method to another as long as their parameters declaration is different this is called method overloading which provides the polymorphism property.

When an overloaded method called it will execute the method which have same type or number of parameters means it should be different for those methods.

Methods may have different return type but it is not sufficient to distinguish the methods.

//example for method overloading
class OverLoadExample
{
  int addition(int a,int b)
  {
    return a+b;
  }
  double addition(double a, double b)
  {
    return a+b;
  }
  int addition(int a,int b,int c)
  {
    return a+b+c;
  }
  void addition()
  {
    System.out.println("It will not perform addition");
  }

}

public class OverLoadDemo
{
  public static void main(String args[])
  {
    OverLoadExample ole = new OverLoadExample();
    System.out.println("addition of two integer values::"+ole.addition(45,78));
     System.out.println("addition of two double values::"+ole.addition(42.0,73.0));
     System.out.println("addition of three integer values::"+ole.addition(45,78,55));
    ole.addition();
  }
}

Output:

addition of two integer values::123
addition of two double values::115.0
addition of three integer values::178
It will not perform addition

Java provides automatic conversation when there is no exact match in type of parameters.

//example for mismatch types in method overloading
class OverLoadExample
{
  int addition(int a,int b)
  {
    return a+b;
  }
  double addition(double a, double b)
  {
    System.out.println("method for adding two double values");
    return a+b;
  }

  int addition(int a,int b,int c)
  {
    return a+b+c;
  }
  void addition()
  {
    System.out.println("It will not perform addition");
  }

}

public class OverLoadDemo
{
  public static void main(String args[])
  {
    OverLoadExample ole = new OverLoadExample();
    System.out.println("addition of two integer values::"+ole.addition(45,78));
     System.out.println("addition of two double values::"+ole.addition(42.0,73)); 
     System.out.println("addition of three integer values::"+ole.addition(45,78,55));
    ole.addition();
  }
}

Output:

addition of two integer values::123
method for adding two double values
addition of two double values::115.0
addition of three integer values::178
It will not perform addition

  • As Java can convert int to double automatically it will execute, If there is method to add double and int type values then it will execute.
  • Method overloading supports polymorphism as it performs like one interface for many methods.
  • ex: math(), abs() for all data types the name is same.
  • In C we have different method names to perform same action for different data types. So in Java it reduces that complexity and no need to remember all those method names.

Overloading Constructors

Like methods we can overload constructors to use different list of parameters while initializing an object.

/* Here, Box defines three constructors to initialize
 the dimensions of a box various ways.
*/
class Box 
{
 double length;
 double breadth;

 // constructor used when all dimensions specified
 Box(double l, double b) 
 {
  length = l;
  breadth = b;
 }
 // constructor used when no dimensions specified
 Box() 
 {

 // use 0 to indicate
 length = 0; // an uninitialized
 breadth = 0; // box
 }
 // constructor used when cube is created
 Box(double len) 
 {
 length= breadth = len;
 }
 // compute and return volume
 double area() 
 {
 return length*breadth;
 }
}

public class OverloadCons 
{
 public static void main(String args[]) 
 {
 // create boxes using the various constructors
 Box mybox1 = new Box(10, 20);
 Box mybox2 = new Box();
 Box mysquare = new Box(7);


 // get area of first box

 System.out.println("Area of mybox1 is " +mybox1.area());

 // get area of second box

 System.out.println("Area of mybox2 is " +mybox2.area());

   // get area of square

 System.out.println("Area of mysquare is " + mysquare.area());
 }
}

Output:

Area of mybox1 is 200.0
Area of mybox2 is 0.0
Area of mysquare is 49.0

we can see that constructor will execute depends on the parameter list when we are initializing objects followed by new keyword.

Using Objects as Parameters

we can pass objects as parameters to methods.

// Objects may be passed to methods.
class Test {
 int a, b;
 Test(int i, int j) {
 a = i;
 b = j;
 }
 // return true if o is equal to the invoking object
 boolean equalTo(Test o) {
 if(o.a == a && o.b == b) return true;
 else return false;
 }
}
class PassOb {
 public static void main(String args[]) {
 Test ob1 = new Test(100, 22);
 Test ob2 = new Test(100, 22);
 Test ob3 = new Test(-1, -1);
 System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
 System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
 }
}

Output:

ob1 == ob2: true

ob1 == ob3: false

The most common use to pass objects as parameters is in constructors which is useful when we want to initialize one object with the states same as already existed object.

//example for passing object as a parameter to constructor
class Box 
{
 double length;
 double breadth;

 // constructor used when all dimensions specified
 Box(double l, double b) 
 {
  length = l;
  breadth = b;
 }
 // constructor used when no dimensions specified
 Box() 
 {

 // use 0 to indicate
 length = 0; // an uninitialized
 breadth = 0; // box
 }
 }

  // constructor which takes object as parameter
  Box(Box b)
  {
    length = b.length;
    breadth =b.breadth;
  }
 // compute and return volume
 double area() 
 {
 return length*breadth;
 }
}

public class OverloadCons 
{
 public static void main(String args[]) 
 {
 // create boxes using the various constructors
 Box mybox1 = new Box(10, 20);
 Box mybox2 = new Box();
 Box objectbox = new Box(mybox1);

 // get area of first box

 System.out.println("Area of mybox1 is " +mybox1.area());

 // get area of second box

 System.out.println("Area of mybox2 is " +mybox2.area());


   //get area which same as mybox1
   System.out.println("Area of objectbox is " + objectbox.area());
 }
}

Output:

Area of mybox1 is 200.0
Area of mybox2 is 0.0
Area of objectbox is 200.0

Argument Passing

There are two ways of passing arguments to a method while calling that method.

call by value- value is passed as argument so if there are changes made in method there will be no change in value.

call by reference- reference is passed as argument so of we change this then the value will also change.

//example for argument passing
class ArgumentPassingExample
{
   int x=5,y=6;
  void callByValue(int a,int b) //call by value
  {
    a*=10;
    b*=30;
  }
   void callByReference(ArgumentPassingExample e) // call by reference of this class
   {
     e.x*=10;
     e.y*=30;
   }
}

public class ArgumentPassingDemo
{
  public static void main(String args[])
  {
    int a=5,b=6;

    ArgumentPassingExample ape = new ArgumentPassingExample();//initialize the object

    System.out.println("Before calling by value a is::"+a+" b is::"+b);
    ape.callByValue(a,b);

    System.out.println("after calling by value a is::"+a+" b is::"+b);

    System.out.println("Before calling by reference x is::"+ape.x+" y is::"+ape.y);

    ape.callByReference(ape);

     System.out.println("After calling by reference x is::"+ape.x+" y is::"+ape.y);
  }
}

Output:

Before calling by value a is::5 b is::6
after calling by value a is::5 b is::6
Before calling by reference x is::5 y is::6
After calling by reference x is::50 y is::180

Returning Objects

As methods returning data of type it can also return the type of class that we created.

// example for Returning an object.
class Test {
 int a;
 Test(int i) {
 a = i;
 }
 Test mulByTen() {
 Test temp = new Test(a*10);
 return temp;
 }
}
public class RetOb {
 public static void main(String args[]) {
 Test ob1 = new Test(2);
 Test ob2;
 ob2 = ob1.mulByTen();
 System.out.println("ob1.a: " + ob1.a);
 System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.mulByTen();
 System.out.println("ob2.a after second multiplication " + ob2.a);
 }
}

Output:

ob1.a: 2

ob2.a: 20

ob2.a after second increase: 200

Recursion

In Java recursion is the attribute which allows a method to call itself. That method called as recursive.

Finding factorial of a number is the best example for recursion.

// A simple example of recursion.
class Factorial 
{
 // this is a recursive method
 int fact(int n) 
 {
 int result;
 if(n==1) 
   return 1;
    result = fact(n-1) * n; //executes till it returns 1 then it multiply with 2---3.

   return result;
 }
}
public class Recursion 
{
 public static void main(String args[]) {
 Factorial f = new Factorial();
 System.out.println("Factorial of 3 is " + f.fact(3));
  System.out.println("Factorial of 5 is " + f.fact(5));
 }
}

Output:

Factorial of 3 is 6
Factorial of 5 is 120

  • It is bit slow compared to iterative equivalent as it have overhead of additional method callings.
  • Many recursive calls to a method could cause a stack overrun as local variables and parameters are storing in stack.
  • If this happen then Java run-time compiler will throws an exception.

  • It provides clear and simple way for several algorithms example: Quick sort.

we have to use if statement otherwise it will not return from that method.

results matching ""

    No results matching ""