Java - Things to know before your OCJP exam - Overloading

1. Methods can be overloaded on number of arguments and type of arguments.

     public void method(int x){}
public void method(float x){}
public void method(int[] x){}
public void method(String x){}
public void method(int x, float y){}
public void method(int x, float y, int z){}

2. Static methods can be overloaded.

      static public void method(int x){}
static public void method(float x){}
public void method(int[] x){}
public void method(String x){}
public void method(int x, float y){}
public void method(int x, float y, int z){}

3. Constructors can be overloaded. this( ) is used to call constructors in chain.

      ClassTest(){ this(5);}
      ClassTest(int x){this(5.5f);}
      ClassTest(float y){}

4. Methods cannot be over overloaded on the basis of return type alone.

        public void method(int x){} // Compile Time Error - Duplicate Method
public int method(int x){ return 1;} // Compile Time Error - Duplicate Method

5. When overloaded on the co variant types, conflict is resolved by the type of reference.

       public void method(Object x){System.out.println("Object");}
       public void method(String x){System.out.println("String");} 
       
       public static void main(String[] args) {
                   new ClassTest.method((Object)"Hello");  // displays Object.
       }

6. Method can be overloaded with var args.

       void method(int x ){};
       void method(int... x){};

In Case of conflict, specific type is called instead of var args type. method(5) will call first method.

7. No Overloading of variable args with an array of same type. Following results in compile time error

      void method(int... x){}; \\ compile time error: duplicate methods.
      void method(int[] x){};  \\ compile time error: duplicate methods.
    
8. When overloaded on the primitives, method with the larger capacity type is picked in case of conflict.

      void method(double x){};
      void method(char x){};

      method(1); \\ will invoke first method as double can accomodate int