Tuesday, September 22, 2020

Constructors

The constructor in java is mainly for initializing value to object and "not to create object" (new keyword creates object).

class Abc
{
   String a;
   Abc(String s)
     {
        this.a=s;
     }
 }
public static void main(String[] args)
 {
    Abc obj=new Abc("haha");
     System.out.println(obj.a);
  }

------------------------------------------------------------------------------

 Rules for constructor 

1) Name of the constructor must be the name of the class
2)  Return type terminology not applicable for the constructor. (if return type provided then it will be a method it needs to be called).
3)  The only access modifiers applicable for constructors are public, default, private, protected. 

-------------------------------------------------------------------------------

Default constructors

1) Compiler adds a default constructor at the time of compilation (not JVM).
2) Every class including the abstract class will have a default constructor.
3) There won't be both default and customized constructor simultaneously.

Characteristics of default constructor.
  • The default constructor is always a no-args constructor.
  • The access modifier is same as that of class modifier(only public and default)
  • The default constructor consists of only 1 line of code "super()".
[note: the first line of the constructor should always be super() or this() not both simultaneously].

Simple case study: 
1) whenever the constructor is not provided then the compiler automatically adds a default constructor.
        Programmers code                                                            compiler modified code
           class Test                                                                         class Test
            {                                                                                      {
                void Test() {} // this is a method not constructor          void Test() {}
              }                                                                                        Test(){  
                                                                                                          super();
                                                                                                        }
2) whenever the constructor is provided by the user but there is no code (i.e super()/this()) in the first line of the constructor then the compiler adds super() as shown below.
         Programmers code                                       compiler modified code
           class Test                                                   class Test
            {                                                               {
                Test()                                                     Test()
                {}                                                          {
                Test(int i)                                               super();
                 {                                                           }
                    this();                                                 Test(int i)
                  }                                                          {
               }                                                              this(); // nothing changed, 
                                                                              }          //firstline is this();
                                                                              }
3) call to super must always be in the first line of the code else the error is thrown 
    eg: class Test
            {
                Test()
                    {
                        sout.println("blah-blah");
                        super(); //compiler error: the super must be first statement
                     }
             }
    eg: class Test
            {
                Test()
                    {
                        super();
                        this(); //compiler error: call to this must be first line [not both]
                     }
             }
4) Call to super() or this() ( not both at once) must be only in the first line of Constructor and not in any method. [constructor can be called directly through another constructor only].
    eg: class Test
            {
                public void Test() //this is a method not constructor
                    {
                        super(); // only to be called in constructor
                        sout.print("abc");
                     }
             }
--------------------------------------------------------------
Difference between  super(),this() and super, this.
- 1) super() and this() is constructor calls in java whereas super and this are keywords in java to call superclass and current class instance members.
   2) super() and this() can be used only in the constructor and as a first statement whereas this and super can be used anywhere.
    3) we can use either this() or super() at a time not both and that too only once, we can use 'this' and 'super' any number of times.
 [restriction: this and super can be used anywhere except static areas].
---------------------------------------------------------------

Constructor overloading

Constructors with different argument types in the same class are overloaded constructors.

eg: 
       Test()
        {
            Test(int i)
                { //constructor 1
                    this();
                 }
             Test()
                  { //constructor 2
                  }
        }
----------------------------------------------------------------

Constructor inheritance and overriding

Inheritance and overriding concept is not applicable for constructors as child class will not have access to parent class constructor.

-----------------------------------------------------------------

Recursive constructor calls 

The recursive constructor call possibility is checked during every compilation step and not checked run-time.
eg:
public class Test {
Test()
{ //constructor 1
this(10);
}
Test(int i)
{ //constructor 2
this();
}
public static void main(String[] args) {
}
}
Error:(7, 9) java: recursive constructor invocation
[note: the recursion in methods is caught as run-time exception]
----------------------------------------------------------------------------

Parent and child class constructor calls

There needs to be special care taken when child class calls parent class constructor. [it is highly recommended to write no-arg constructor in parent class always]
public class Parent {
Parent(int i)
{}
}
class Child extends Parent
{
Child()
{
//it implicitly calls super()
}
}
 Error: There is no default constructor available in 'Parent'.
-------------------------------------------------------------------------

Throws clause with constructor

If the parent class constructor throws any checked exception then the child class should throw the same checked exception or its parent.
eg:
public class Parent {
Parent() throws IOException
{}
}
class Child extends Parent
{
Child() throws IOException // or throws Exception also works
{
}
}

SOLID principles in java

SOLID  Single responsibility principle : a class should have only  reason to change, i.e. a class should have only one responsibility/single...