Thursday, February 4, 2016

Why constructors cannot be final, static and abstract?

Why constructors cannot be final, static and abstract?

public class FinalConstructor {

     abstract static final synchronized private FinalConstructor() {

     }
}

Constructors can’t be final because when we use final with methods , that means method can’t be override. Constructors by Java rules can’t be override anyways , so no point in making constructors as final.

Constructors can’t be static because constructors in java are used to instantiate object (in use with new keyword) whereas static keyword is used for class variables and not object.

Constructors can’t be abstract because when you set a method as ‘abstract’, it means method doesn't have any body and you want to implement it at another time in a child class, but the constructor is called implicitly when the new keyword is used so it can’t lack a body.

Facts to know about Constructors

·     Chain hierarchy of Constructor    By default every constructor call their parent class' no argument constructor in            first line e.g super().

·       Constructor is not inherited in Java
    This is an interesting but non obvious information about constructor. When you         create a child class in Java, it inherits member variables, non final and non static          methods but not constructors. They belong to the class they are declared.

·        Static initializer and instance initializer block is executed before constructor.
    If you don't know how a class is loaded and initialize, read this. Apparently static       initializer is executed at the time of class loading and instance initializer block of a    class is executed before constructor of that class, but only after successful execution    of constructor from super class. If your parent class constructor throw exception          then instance initialization block will not execute. 

No comments:

Post a Comment