← Back to feed
Renewal·서른의 생활코딩

ex2) java_oop

NS
normalstory
cover image



// Overloaded functions
// : when constructor or member functions with the same name are created inside a single class
//   The number and types of parameters must be different.
//   Execution automatically resolves to the matching parameter count and type.
//   Implemented within the scope of a single class.

public class Fun01 {
 
     //Add(int a,int b){return a+b;}
     int Add(int a,int b){return a+b;}
     double Add(double a,double b){return a+b;}
 
     //Add(double a,int b){return a+b;}
     double Add(double a,int b){return a+b;}
     double Add(int a,double b){return a+b;}

     //  The return type can be different, such as int or double.
     //  Different parameter names alone do not make a function overloaded.

     //  A different number of parameters can also make it an overloaded function.
     double Add(int a,double b,int c){return a+b+c;}

     public static void main(String[] args) {
     // Since this is not a static member function, define an object first and access it through that object.
     // If there is no member function, the JVM creates and uses Fun01(){}.
     // If even one constructor with parameters exists, the JVM does not create a default constructor.
     Fun01 f = new Fun01();
  
     //System.out.println(Add(10.5,20));
     System.out.println(f.Add(10.5,20));
     System.out.println(f.Add(10.5,20.5));
     System.out.println(f.Add(10,20));
     System.out.println(f.Add(10,20.5));

     //   A different number of parameters can also make it an overloaded function.  
     System.out.println(f.Add(100,20.5,50));
     }
     // Overloading and overriding are different concepts.
}

This English version was translated by Codex.

친절한 찰쓰씨
Written by
친절한 찰쓰씨

Pleasant Charles — UI/UX researcher at AIT. Keeping notes on design, planning, and slow days here since 2010.