All About Constructors

0
1118

Constructor of a class means declaring and defining a method with the same name of that of the class with no return value. It is primarily used to set the initial values for the class level attributes (also known as fields) and is the first one to get called when an object of a class gets created. The constructor must be called every time you create a new object of a class.

Interesting facts about constructor

If you do not declare a constructor within a class, java creates a no argument constructor for every class you write (this is also known as default constructor). But remember, if you declare a constructor for a class accepting some arguments or otherwise then java will not write the default constructor for you. In that case if you need a no argument constructor, you have to write one of your own. Also to note that an abstract class has a default constructor if you do not specify one explicitly.

It means every class has an associated constructor irrespective of you write it or not. The basic principle to write a constructor –

a) It should hold the exact same name of the class (case-sensitive) and,
b) Must not return any value (not even void type)

Simple Example of Non-argument and Argument Constructor

Class GoyalsBit {
    private String name;
    private int age;
    //No-Argument or Default Constructor
    public GoyalsBit(){

    }
    //Argument Constructor
    public GoyalsBit(String nameInArg, int ageInArg){
        this.name = nameInArg;
        this.age = ageInArg;
    }
}

More Facts

Lets see what all you need to know about constructors. These points are many a times covered in interviews as well to test the fundamental knowledge:

  • It is legal to have a method with the same name as the class (if it is having a return type)

  • If you don’t provide a call to super class constructor, compiler inserts it as the first statement in the subclass constructor . (At least to call object’s class’ default constructor)

  • You cant make a call to an instance method or access an instance variable until after super Constructor runs.

  • Constructor is never inherited.

  • Only static variables and methods can be accessed as part of the call to super() or this()
    ex:  super(Building.name) is OK if ‘name’ is static

  • Interfaces don’t have a constructor(not even default).

  • A constructor cannot be invoked from any method as normal method call but it could be invoked from within another constructor.

  • If your super class constructor is having arguments and you are not providing a non-arg constructor then while calling Super() from subclass constructor, you must pass the arguments. Otherwise compiler error will be shown as there is no default constructor. This call must be the first line in the child class constructor.

Example:

Class Notebooks {
Notebooks(String s) {}
}

Class SonyLaptops extends Notebooks {
}

Result: Compiler Error; as there is no Call to Super Class’ arg-constructors. You have to call explicitly as there is no default constructor in super class. The first line in a constructor must be a call to super() or this():

Class Notebooks {
    Notebooks(){
    }
}

Class SonyLaptops extends Notebooks {
    SonyLaptops(){
        super();
    }
}

 

What about Static Methods?

We can call static methods from a constructor, even before the call of super().

Example:

public class Laptops{
    String name;
    
    Laptops(String name){
        this.name=name;
    }

    //Call static method from within a constructor
    Laptops(){
        this(createAnyName());
    }
    
    //Static Method
    static String createAnyName(){
        System.out.println("I am a static Method");
        return "testStatic";
    }
}

As default no-arg constructor calls this(), super() will be called little later. i.e. in the arg-constructor.

Call to super() and this():

A constructor can never have both a call to super() and this(). Because each of those calls must be the first statement in the constructor. You can’t legally use both in the same constructor.

Example:

Class Laptop{
    Laptop(){
        this(Arg Constructor);
    }

    Laptop(String name){
        this();
    }
}

In the above example, both the constructors are calling each other here, so you would get java.lang.StackOverflowError.

Please let me know if you are looking for some specific information around constructors which I have not covered here. I would be happy to include that as well 🙂

 

Previous articleBasic Java Questions
Next articleException Handling Questions
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY