Constructors in java.

  • A Java constructor is special method that is called when an object is instantiated.
  • In other words, when you use the new keyword.
  • The purpose of a Java constructor is to initializes the newly created object before it is used.
  • This Java constructors tutorial will explore Java constructors in more detail.
Here is a simple example that creates an object, which results in the class constructor being called:
MyClass myClassObj = new MyClass();

This example results in a new MyClass object being created, and the no-arg constructor of MyClass to be called. 

  • A Java class constructor initializes instances (objects) of that class.
  • Typically, the constructor initializes the fields of the object that need initialization.
  • Java constructors can also take parameters, so fields can be initialized in the object at creation time.
    public class MyClass {
    
        public MyClass() {
    
        }
    }
    The constructor is this part:
    
        public MyClass() {
    
        }

    Constructor overloading example :

    public class MyClass {
    
        private int number = 0;
    
        public MyClass() {
        }
    
        public MyClass(int theNumber) {
            this.number = theNumber;
        }

Posted on by