What is constructor in java ?

A constructor is a special method used to initialize objects in java.

We use constructors to initialize all variables in the class when an object is created. As and when an object is created it is initialized automatically with the help of constructor in java.

We have three types of constructors

  1. Default Constructor
  2. No-arg constructor
  3. Parameterized Constructor

Example:-

class Example2 {
    private int var;
    //default constructor
    public Example2() {
        this.var = 10;
    }
    //parameterized constructor
    public Example2(int num) {
        this.var = num;
    }
    public int getValue() {
        return var;
    }
    public static void main(String args[]) {
        Example2 obj = new Example2();
        Example2 obj2 = new Example2(100);
        System.out.println("var is: " + obj.getValue());
        System.out.println("var is: " + obj2.getValue());
    }
}

Output:-

var is: 10
var is: 100

 

Recent Posts

Explain Platform?

Any hardware or software environment in which a program runs, is known as a platform.…

5 years ago

What is Multi-threading in Java?

Multi-threading is a Java feature that allows concurrent execution of two or more parts of…

5 years ago

What is ‘IS-A’ relationship in java?

'is a' relationship is also known as inheritance. We can implement 'is a' relationship or…

5 years ago

Explain Java Coding Standards for Constants?

Constants in java are created using static and final keywords. Constants contains only uppercase letters.…

5 years ago

Explain Java Coding Standards for variables ?

Variable names should start with small letters. Variable names should be nouns. Short meaningful names…

5 years ago

Explain Java Coding standards for Methods?

Method names should start with small letters. Method names are usually verbs If method contains…

5 years ago