Constructors

What is Constructor?

Constructor is used to initialize the objects. new keyword always call constructor of the class in the java code.
  • Every class has a constructor. 
  • If we do not explicitly write a constructor for a class then Java compiler builds a default constructor for that class.
  • Each time a new object is created, at least one constructor will be invoked. 
  • The constructors have the same name as the class. 
  • A class can have more than one constructor.
  • Constructor is use to assign values to instance variables.
  • Constructor does not have return type.
Constructor in Java


Example:
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

1
2
3
4
5
6
7
8
9
class Bike {
 Bike() {
  System.out.println("Bike is created");
 }

 public static void main(String args[]) {
  Bike b = new Bike();
 }
}

In this example, we are creating the constructor in the Dog class and passing the arguments to the constructor. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Dog {

 String name;

 public Dog(String name) {
  this.name = name;
  System.out.println(name);
 }

 public static void main(String[] args) {
  Dog d = new Dog("puppy_1");
 }
}

Note: If there is no constructor defined in a class, then compiler automatically creates a default constructor.
Constructor in Java
Why java doesn’t support static constructor?
  • The main purpose of a constructor is to initialize the object variables. If we make constructor as static then it won’t be able to initialize the object variables.  That will defeat the whole purpose of having a constructor for creating the object. So it is justified to have the constructor as non-static.
  • Another example, if we are calling static constructor of parent's class from child class using super method  then constructor becomes static, we won’t be able to use it and that will break inheritance in java.
Can we override constructor?
  • No , constructor can never be overridden . It's because constructor acts at class level and it's unique for each class created in Java or any OOP language. 
  • If we try to override the constructor of parent class in child class then it won’t be able to identify the method. Since the scope of constructor is limited to the class itself.

Why Constructors are not inherited in Java?
  • Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name.

<-- Previous || Next -->

No comments:

Post a Comment