CodesJava

Easy learning with example program codes

Constructor in java


Constructor: 

Constructor is a special member of a class which is used to initialize the state of an object. It provides the values to the data members at the time of object creation that is why it is known as constructor.

Characteristics of constructor: 

  1. A constructor must have the same name as of its class.
  2. It is invoked at the time of object creation and used to initialize the state of an object.
  3. It does not have an explicit return type.

Types of constructor:

  1. Default or no-argument constructor.
  2. Parameterized constructor.

Default or no-argument constructor:

A constructor with no parameter is known as default or no-argument constructor. If no constructor is defined in the class then compiler automatically creates a default constructor at the time of compilation.

 Syntax:

Class_name(){

       //optional block of code

}

Why default constructor is used?

Default constructor is used to provide default values to the object properties i.e. to provide default state of an object.

Example:

/**
 * This program is used to show the use of default constructor.
 * @author CodesJava
 */
public class ConstructorExample1 {
                int num;
                String str;
                ConstructorExample1(){
                       System.out.println("Constructor called.");
                }
 
                public static void main(String args[]){
                       //constructor call
                       ConstructorExample1 obj1 = 
                                      new ConstructorExample1();
 
                       //print default values of object properties.
                       System.out.println("num = " + obj1.num);
                       System.out.println("str = " + obj1.str);
                }
}

Output:

Constructor called.
num = 0
str = null

Download this example.

Note: If no constructor is defined in the class then compiler automatically creates a default constructor at the time of compilation. 

Example:

/**
 * This program is used to show that compiler will automatically
 * creates the default constructor if not defined.
 * @author CodesJava
 */
public class ConstructorExample2 {
                int num;
                String str;               
 
                public static void main(String args[]){
                       //constructor call, compiler will automatically
                       //creates the default constructor
                       ConstructorExample2 obj1 = 
                                      new ConstructorExample2();
 
                       //print default values of object properties.
                       System.out.println("num = " + obj1.num);
                       System.out.println("str = " + o Dismiss bj1.str);
                }
}

Output:

num = 0
str = null

Download this example.

 Parameterized constructor:

A constructor with one or more arguments is known as parameterized constructor.

Why parameterized constructor is used?

Parameterized constructor is used to provide values to the object properties. By use of parameterized constructor different objects can be initialize with different states.

Example:

/**
 * This program is used to show the use of parameterized constructor.
 * @author CodesJava
 */
public class ConstructorExample3 {
                int num;
                String str;
 
                ConstructorExample3(int n, String s){
                      System.out.println("Constructor called.");
                      num = n;
                      str = s;
                }
 
                public static void main(String args[]){
                     //constructor call
                     ConstructorExample3 obj1 = 
                          new ConstructorExample3(10, "CodesJava");
 
                     //print values of object properties
                     System.out.println("num = " + obj1.num);
                     System.out.println("str = " + obj1.str);
                }
}

Output:

Constructor called.
num = 10
str = CodesJava

Download this example.

Note: If a class contains parameterized constructor and default constructor is needed than default constructor has to be defined explicitly. In this case compiler will not provide default constructor. 

Example:

/**
 * This program is used to show that if a class contains
 * parameterized constructor and default constructor is needed
 * than default constructor has to be defined explicitly. In this
 * case compiler will not provide default constructor.
 * @author CodesJava
 */
public class ConstructorExample4 {
                int num;
                String str;
                ConstructorExample4(int n, String s){
                     System.out.println("Constructor called.");
                     num = n;
                     str = s;
                }
 
                public static void main(String args[]){
                    //constructor call
                    ConstructorExample4 obj1 = 
                          new ConstructorExample4(10, "javawithease");
 
                    //error, because in this case default constructor
                    //will not be provided by compiler.
                    ConstructorExample4 obj2 = new ConstructorExample4();
 
                    //print values of object properties.
                    System.out.println("num = " + obj1.num);
                    System.out.println("str = " + obj1.str);
                }
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The constructor ConstructorExample4() is undefined
at com.codesjava.business.ConstructorExample4.main
(ConstructorExample4.java:23)

Download this example.

Constructor overloading in java.

The process of defining more than one constructor with different parameters in a class is known as constructor overloading. Parameters can differ in number, type or order.

Example:

/**
 * This program is used to show the use of constructor overloading.
 * @author CodesJava
 */
public class ConstructorExample5 {
       int num;
       boolean isStudent;
       String str;
 
 
       //One argument constructor
       ConstructorExample5(boolean boolean1){
       System.out.println("One argument constructor called.");
          isStudent = boolean1;
       }               
 
       //Two argument constructor
       ConstructorExample5(int n, String s){
        System.out.println("Two argument constructor called.");
        num = n;
        str = s;
       }    
 
       //Three argument constructor
       ConstructorExample5(boolean boolean1, int n, String s){
         System.out.println("Three argument constructor called.");
         isStudent = boolean1;
         num = n;
         str = s;
        }
       public static void main(String args[]){
         //one argument constructor call
         ConstructorExample5 obj1 = new ConstructorExample5(true);
 
         //print values of object properties.
         System.out.println("isStudent = " + obj1.isStudent);
         System.out.println("num = " + obj1.num);
         System.out.println("str = " + obj1.str); 
 
         //two argument constructor call
         ConstructorExample5 obj2 = 
               new ConstructorExample5(10, "CodesJava");
 
          //print values of object properties.
          System.out.println("isStudent = " + obj2.isStudent);
          System.out.println("num = " + obj2.num);
          System.out.println("str = " + obj2.str);
 
          //three argument constructor call
          ConstructorExample5 obj3 = new
          ConstructorExample5(false, 20, "CodesJava.com");
 
          //print values of object properties.
          System.out.println("isStudent = " + obj3.isStudent);
          System.out.println("num = " + obj3.num);
          System.out.println("str = " + obj3.str);
        }
}

Output:

isStudent = false
num = 20
str = CodesJava.com

Download this example.

 Difference between constructor and method.

            Constructor               Method
  1. It has same name as of class.
  2. Invoked implicitly.
  3. Must not have any explicit return type.
  4. It is used to initialize the state of an object.
  1. It may or may not have same name as of class.
  2. Invoked explicitly.
  3. Must have a return type.
  4. It is used to show behavior of an object.
Note: An object can also perform any operation like any other method.

Does a constructor return any value?

Yes, a constructor implicitly returns the instance of the current class.

How to copy the values one object into another object using constructor?

Example:

/**
 * This program is used to copy the values one object
 * into another object using constructor.
 * @author CodesJava
 */
public class ConstructorExample6 {
       int num;
       String str;               
 
       ConstructorExample6(int n, String s){
            System.out.println("Constructor called.");
            num = n;
            str = s;
       }
 
        //This constructor will copy the value
        //of one object into another.
        ConstructorExample6(ConstructorExample6 obj){
            System.out.println("Constructor called
                                  for copying value.");
            num = obj.num;
            str = obj.str;
        }
 
        public static void main(String args[]){
           //parameterized constructor call
           ConstructorExample6 obj1 = new
                 ConstructorExample6(10, "CodesJava");
 
           //print values of object properties.  
           System.out.println("obj1 num = " + obj1.num);
           System.out.println("obj1 str = " + obj1.str);
           //Constructor call to copy the value
           //one object into other.
           ConstructorExample6 obj2 = new ConstructorExample6(obj1);
           //print values of object properties. 
           System.out.println("obj2 num = " + obj2.num);
           System.out.println("obj2 str = " + obj2.str);
       }
}

Output:

Constructor called for copying value.
obj2 num = 10
obj2 str = CodesJava

Download this example.
 
Next Topic: Package in java.
Previous Topic: Custom marker Interface in java with example.

Related Topics:

Command line arguments in java with example.
How to execute command line argument program in eclipse.
How to read input from command line in Java using Scanner.
Abstract class in java with example.
Interface in java with example.
Custom marker Interface in java with example.
Constructor in java with example.

 

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap