0
7.0kviews
Short note on Constructor and its types

Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology

Marks: 5 M

Year: May 2015

1 Answer
1
61views

Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially. It is optional to write constructor method in a class but due to their utility they are used.

Types of java constructors

There are two types of constructors:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

enter image description here

Default Constructor:

A constructor that has no parameter is known as default constructor. Default constructor provides the default values to the object like 0, null etc. depending upon the type.

Syntax of default constructor:

<classname> () 

{   }

Example for default constructor:

class Bike1{  
Bike1(){System.out.println("Bike is created");}  
public static void main(String args[]){  
    Bike1 b=new Bike1();  
}  
}

Parameterized constructor:

A constructor that have parameters is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects.

In below example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.  

Import java.io.*;
Import java.util.*;
class Student4{  
    int id;  
    String name;  

    Student4(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  

    public static void main(String args[]){  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    s1.display();  
    s2.display();  
   }  
}
Please log in to add an answer.