Exact need of Method Overloading in Java [duplicat

2019-07-10 05:43发布

问题:

This question already has an answer here:

  • Why is method overloading and overriding needed in java? [duplicate] 3 answers

Since I have found so many examples and conclusions about Method Overloading but still I am confusing in real time how we are using it.

First of all method overloading is a class level activity means within that class we are overloading a method with same name but different arguments like

void sum(int a,int b){System.out.println(a+b);}  
void sum(double a,double b){System.out.println(a+b);} 

and after we are calling this method like

public static void main(String args[]){  
ClassName obj=new ClassName ();  
obj.sum(10.5,10.5);  
obj.sum(20,20);  
}  

Suppose instead of this I will take two separate method like

void method1(int a,int b){System.out.println(a+b);}  
void method2(double a,double b){System.out.println(a+b);} 

And I will call this 2 methods same as above

public static void main(String args[]){  
ClassName obj=new ClassName (); 
obj.method1(20,20);   
obj.method2(10.5,10.5);  
} 

In both the case for both the methods the activities are same then what is the exact need of overloading/polymorphism in this case.

Somewhere I found that Method overloading increases the readability of the program can anybody please specify that only because of this line we are using method overloading.

Thanks.

回答1:

Suppose we didn't have method overloading in Java.

Instead of :

System.out.println("String");
System.out.println(5);
System.out.println('c');
...

we would have :

System.out.printlnString("String");
System.out.printlnInt(5);
System.out.printlnChar('c');
...

or even worse :

System.out.println1("String");
System.out.println2(5);
System.out.println3('c');
...

Both alternatives would make the code less readable.



回答2:

You can check the existed Java API like Math, Arrays to see the power of Overload.

Do you want to remember each method name depends on your data type or just use Arrays.sort() and let language itself decides which implementation should be used depends on the parameter?

Arrays.sortByte(byte[] abyte)

Arrays.sortChar(char[] ac)

Arrays.sortFloat(float[] af)

Arrays.sortDouble(double[] ad)

Arrays.sortShort(short[] as)

Arrays.sortInt(int[] ai)

Arrays.sortLong(long[] al)

For some other scenario, you may have dozens of methods that have same function but the implementation just vary a little based on dozens of combination of parameters, the situation will become worse if you do not use Overload.

Same discussion has already been discussed in this thread.

Why should I ever overload methods?



回答3:

Method overloading can also help API designers to provide different levels of abstraction.

For example, she can choose to provide a beginner version, where most parameters are given default values that works well in most case, in parallel with an expert version where the user can fine-tune the parameter to suit their particular needs:

/*
 * A beginner version that just works.
 */
public void foo() {
    foo(1, 2);
}

/*
 * An expert version where the user has more control over the
 * parameters, requiring more knowledge about the API.
 */
public void foo(int a, int b) {
}

A real world example from HashMap.java:

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

Usually the user do not need to play with the initialCapacity and loadFactor parameters, but they can if needed.



回答4:

Yon can find more details about overloading methods in oracle documentation page.

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type.

It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on.

In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.

The note provided in documentation page exactly opposite to your statement (overloading increases code readability)

Note: Overloaded methods should be used sparingly, as they can make code much less readable.

Have a look at one example.

Assume that you have to shift a Shape by its parameters : length, width and height.

Square passes it's length as parameter.

Rectangle passes it's length and width as parameter.

One more 3D shape passes it's length, width and height.

    public void shiftPosition(int length){
        shiftPosition(length,0,0);
    }
    public void shiftPosition(int length,int width){
        shiftPosition(length,width,0);
    }
    public void shiftPosition(int length, int width, int height){
        System.out.println("Shfit Position by length:width:height:"+
        length+":"+width+":"+height);
    }

The sifhtPosition is a overloaded method with three different signatures.

Assume a scenario, where you have 8 different versions of the same method. If you try to find the references of each individual method across the project classes for code refactoring, you will realize that it's a big mess.

This javaworld articles explains about costs and dis-advantages of method overloading.



回答5:

Here is an example of why method overloading is necessary in order for developers like us to be able to use them effieciently:

In the Graphics2D class in java there is a method called drawImage, although it has an overload as shown below: abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) abstract void drawImage(Image img, AffineTransform xform, ImageObserver obs)

Suppose that instead of being organized as shown below, they were labeled drawImage1 and drawImage2, that would make it so that any version of drawImage has a completely different name for you to remember thus meaning you could potentialy end up having to remember many names of every drawImage method instead of simply knowing what parameters are acceptable. Therefore, method overloads provide developers with the different methods that have different functionality, but the same name because they essentially do the same thing, but require different parameters to do it just like the drawImage overload.