Write a java program demonstrating Method overloading and Constructor overloading

Program: Write a java program demonstrating Method overloading and Constructor overloading.

Aim: Introduce concepts of method overloading, constructor overloading, and overriding.

Program 1:-

Demonstrating Method overloading

class MOverloading {
    //adding two integer numbers 
    int add(int a, int b) {
        int sum = a + b;
        return sum;
    }
    //adding three integer numbers 
    int add(int a, int b, int c) {
        int sum = a + b + c;
        return sum;
    }
    float add(float a, float b) {
        float sum = a + b;
        return sum;
    }
}
class MOverload {
    public static void main(String args[]) {
        MOverloading obj = new MOverloading();
        int s1 = obj.add(10, 20);
        int s2 = obj.add(10, 20, 30);
        float s3 = obj.add(2.2 f, 2.2 f);
        System.out.println("Method Overload Sum1=" + s1);
        System.out.println("Method Overload Sum2=" + s2);
        System.out.println("Method Overload Sum3=" + s3);
    }
}

Output:-


Program 2:-

Constructor Overloading

public class Constructor 
{ 
    int id; 
    String name; 
    Constructor() 
    { 
        System.out.println("This is Default constructor"); 
        System.out.println("Student Id : "+id + "\nStudent Name : "+name); 
    } 
    Constructor(int i, String n) 
    { 
        System.out.println("This is Parameterized Constructor:"); 
        id = i; name = n; 
        System.out.println("Student Id : "+id + "\nStudent Name : "+name); 
    } 
    public static void main(String[] args) 
    { 
        Constructor s = new Constructor(); 
        Constructor student = new Constructor(10, "David"); 
    } 
}   

Output:-

Leave a Reply

Your email address will not be published. Required fields are marked *