WHAT'S NEW?

Constructor in Java

Constructor

Constructor are special type of methods which have name same as class name.
Constructors are required to instantiate an object.
Every class have a constructor .


Constructors are methods so here are some of the characteristics of constructors.

  1. Constructors name is exactly same as class name. EVEN CASES SHOULD MATCH
          public class Pen
          {

          Pen()
         {
         }

          }

    2. Constructor do not have return type, not even void.

Normal Method v/s Constructor

        3. Constructor can be overloaded. 

            There can be more than one constructor in a class.
            
         class Pen 
       {
Pen()
{
System.out.println("Pen");
}

Pen(String refillColor)
{
System.out.println("Pen Refill Color Is:"+refillColor);
}
Pen(int refillLevel)
{
System.out.println("Pen Refill Level Is:"+refillLevel);
}

Pen(String refillColor,int refillColor)
{
System.out.println("Pen Refill Color Is:"+refillColor+"\nPen Refill Level Is:"+refillLevel);
}

       }

     4. Constructor can  be parameterized as well as non parameterized.


 Every Class have a Constructor

- Every single class in Java have a constructor. Even if it not typed we get a free constructor at runtime.

Let us try to understand with an example.

Car.java

class Car 
{
public  void run()
{
System.out.println("Run of Car");
}

}

Demo.java

class Demo 
{
public static void main(String[] args) 
{
Car c=new Car();
c.run();
}
}

If you try to run this class. It will compile and run fine but try understand the blue marked line.
It is the call to the constructor.
But  if we check properly the class Car it does not contain  any constructor definition inside it.

So from where does it get it?       

When a class is compiled and if the class do not have any constructor definition in it, compiler at runtime generates a default constructor in it which is devoid of any code.

Difference in class having constructor and class not having constructor


- So a simple rule to remember. If your class have no constructor you will get a default constructor from compiler, but if you provide any constructor in your class i.e. Default or parameterized you are not going to get any constructor from compiler. Make that point clear.

If no constructor , Compiler gives us one.
Even one constructor or many, No constructor from compiler.


- Constructors do not get inherited.


More the Constructors in class , More Flexible is the code as we get as many options for  instantiating the class.



0 comments:

Post a comment