Slide 1
Slide 2
Slide 3

Constructors in java programming (V58)

No Comments

Constructors

Constructors are a special type of method used to initialize an object when it is created. They have the same name as their class and are similar to methods. However, constructors do not have an explicit return type.

Typically, you use a constructor to provide initial values to the instance variables defined by the class or to perform other start-up procedures required to create a fully initialized object.

All classes have constructors, whether you define one or not, because Java provides a default constructor that automatically initializes all member variables to zero. However, when you define your own constructor, the default constructor is no longer used.

 Rules for Creating Constructors

You must follow the rules given below while creating constructors:

  • The name of the constructor must be the same as the class name.
  • Constructors do not have a return type, not even void.
  • There can be multiple constructors in the same class; this concept is known as constructor overloading.
  • Access modifiers can be used with constructors if you want to change their visibility/accessibility.
  • Java provides a default constructor that is called during object creation. If you create any type of constructor, the default constructor (provided by Java) is not called.

Types of Constructors

1. Default Constructor – no parameters.

2. Parameterized Constructor – accepts parameters to initialize fields.

Source Code1: Constructor.java

Copied!
public class Constructor {
    String name;

    // Constructor
    public Constructor() {
        name = "Unknown";
    }

    public void display() {
        System.out.println("Name: " + name);
    }

    public static void main(String[] args) {
        Constructor s1 = new Constructor(); // Constructor is called here
        s1.display();
    }
}

Result:



Watch the video:




back to top