Tuesday, 1 September 2015

Method Overloading

Method Overloading

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.

Alternatively, we can use four methods named draw with different parameter list.

Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.

public class DataArtist {
    ...
    public void draw(String s) {
        ...
    }
    public void draw(int i) {
        ...
    }
    public void draw(double f) {
        ...
    }
    public void draw(int i, double f) {
        ...
    }
}

static String valueOf(boolean b)
       static String valueOf(char c)
       static String valueOf(char[] data)
       static String valueOf(char[] data, int offset, int count)
       static String valueOf(double d)
       static String valueOf(float f)
       static String valueOf(int i)
       static String valueOf(long l)
       static String valueOf(Object obj)

This means that if we have any type of variable, we can get a String representation of it by using String.valueOf(variable).


draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...