Easy Tutorial
❮ Java Collections Java9 New Features ❯

Java Example - Method Overloading

Java Examples

First, let's look at the definition of method overloading: If two methods have the same name but different parameters, then one method is considered an overload of the other. Here is the specific explanation:

The following example demonstrates how to overload the info method of the MyClass class:

MainClass.java File

class MyClass {
    int height;
    MyClass() {
        System.out.println("No-argument constructor");
        height = 4;
    }
    MyClass(int i) {
        System.out.println("House height is " + i + " meters");
        height = i;
    }
    void info() {
        System.out.println("House height is " + height + " meters");
    }
    void info(String s) {
        System.out.println(s + ": House height is " + height + " meters");
    }
}
public class MainClass {
    public static void main(String[] args) {
        MyClass t = new MyClass(3);
        t.info();
        t.info("Overloaded method");
        // Overloaded constructor
        new MyClass();
    }
}

The output of the above code is:

House height is 3 meters
House height is 3 meters
Overloaded method: House height is 3 meters
No-argument constructor

Java Examples

❮ Java Collections Java9 New Features ❯