Thursday, May 8, 2014

All about Java Constructors

1) Constructors can have only public,private,protected and default access modifiers. final,abstract,static keywords are not allowed.

                                        public  abstract Constructor() {

                                         }


2)Constructors do no have a return type.If it has a return type then it becomes a method, showing a warning that "The method has the constructor name".

                                        public void  Constructor() {

                                         }

3)Constructors can have any number of parameters  and can be of any type. But only final modifier is allowed for the parameters.

public Constructor(int a,String b,boolean c,final String d,int e,transient String f) {
System.out.println("Invoking constructor");
}

Here, transient keyword is not allowed. Only final modifier is allowed.

4)You can call one constructor from the other using 'this'

                                  public Constructor(int a) {
                                   this();
                                   System.out.println("Parameterized constructor");
                             }
this() will call the default constructor.
                                 public Constructor() {
                                System.out.println("Default constructor");
                             }

5) If you are calling this() then the default constructor should be implemented. Else it will give "default constructor undefined".

6)Now what happens if we do like this :

                                  public Constructor(int a) {
                                      this();
                                     System.out.println("Parameterized constructor");
                             }
this() will call the default constructor.

                                 public Constructor() {
                                          this(2);
                                        System.out.println("Default constructor");
                             }
this(2) will call the parameterized constructor.

It is not allowed as it will result in loop. It is a compile time error "Recursive Constructor Invocation".

7) When there are two classes say, A and B where B extends A then we should follow the below rules
      1. If a subclass B wants to invoke super class A default constructor then "super()"  method should be used. No need to define the default constructor in super class.
      2. Even if we do not mention super() in any of the constructors, the default constructor of the super class is called by default. This does not apply for the parameterized constructor.
      3. If a subclass B wants to invoke super class A parameterized constructor then super(parameters) should be used. The super class default and parameterized constructors should be defined. Else it will show compile time error.



















No comments:

Post a Comment