JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java Constructor Overloading Examples

Like method overloading we can overload constructors also. Along with default constructor, we can have constructors with parameters. The no of parameters can be same, and it can have different datatypes. Below example gives sample code for constructors overloading.

Java Constructor Overloading Sample Code

Code:
package com.myjava.constructors;

public class MyOverloading {
    
    public MyOverloading(){
        System.out.println("Inside default constructor");
    }
    public MyOverloading(int i){
        System.out.println("Inside single parameter constructor with int value");
    }
    public MyOverloading(String str){
        System.out.println("Inside single parameter constructor with String object");
    }
    public MyOverloading(int i, int j){
        System.out.println("Inside double parameter constructor");
    }
    
    public static void main(String a[]){
        MyOverloading mco = new MyOverloading();
        MyOverloading spmco = new MyOverloading(10);
        MyOverloading dpmco = new MyOverloading(10,20);
	MyOverloading dpmco = new MyOverloading("java2novice");
    }
}

Example Output

Inside default constructor
Inside single parameter constructor with int value
Inside double parameter constructor
Inside single parameter constructor with String object

Other Constructor Examples

Knowledge Centre
Inner class and Anonymous class
Inner class: classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.

Anonymous class: Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.