How to overload methods in Java



Problem Description

How to overload methods?

Solution

This example displays the way of overloading a method depending on type and number of parameters.

class MyClass {
   int height;
   MyClass() {
      System.out.println("bricks");
      height = 0;
   }
   MyClass(int i) {
      System.out.println("Building new House that is " + i + " feet tall");
      height = i;
   }
   void info() {
      System.out.println("House is " + height + " feet tall");
   }
   void info(String s) {
      System.out.println(s + ": House is " + height + " feet tall");
   }
}
public class MainClass {
   public static void main(String[] args) {
      MyClass t = new MyClass(0);
      t.info();
      t.info("overloaded method");
      
      //Overloaded constructor:
      new MyClass();
   }
}

Result

The above code sample will produce the following result.

Building new House that is 0 feet tall.
House is 0 feet tall.
Overloaded method: House  is 0 feet tall.
bricks

The following is an another sample example of Method Overloading

public class Calculation {
   void sum(int a,int b){System.out.println(a+b);}
   void sum(int a,int b,int c){System.out.println(a+b+c);}

   public static void main(String args[]){
      Calculation cal = new Calculation();
      cal.sum(20,30,60);
      cal.sum(20,20);
   }
}

The above code sample will produce the following result.

110
40
java_methods.htm
Advertisements