2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Java reluctant constructor

In general code world we used to got chance to see throws in common methods. But, very less chance to see a throws in constructors. Lets have a look into below code:

public class ReluctantConstructor {
    
    private ReluctantConstructor reluctantConstructorVar = new ReluctantConstructor();
    
    public static void main(String[] args) {
        try {
            ReluctantConstructor reluctantConstructor = new ReluctantConstructor();
            System.out.println("I cant belive, this can happened.");
        } catch(Exception e){
            System.out.println("But this really happened man...");
        }
    }
    
    public ReluctantConstructor() throws Exception{
        throw new Exception("man i am throwing Exception.");
    }
}

The main method of ReluctantConstructor() throwing Exception, where we might expect it will print "I cant believe, this can happened.". But if we see in depth of the code will be able to see there ReluctantConstructor() constructor creating an internal instance of ReluctantConstructor() which again creating and internal instance of ReluctantConstructor() and so on. Now if we see, the final result will be StackOverflowException. As we can see it contains infinity internal instance which will keep creating the instance and finally will give StackOverflowException.

It is uncommon in normal coding world to contain instance/object of same type.

Instance variables always initialize before constructor. If any exception occurred in instance initializer propagate to constructor. if initialization throw checked exception constructor must be declared to throw checked exception.