Every class has a constructor whether it is normal one or a abstract class.constructor are not methods and they do not have any return type.Constructor name and class name should be the same.

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.


simple example that uses a constructor:

// A simple constructor.
class employee
{
int code;
String name;
employee()
{
code=0;
name="srinivas";
}
void show()
{
system.out.println("code="+code);
system.out.println("name="+name);
}
}
class const1
{
employee emp=new employee();
emp.show();
}
}

Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name.


Default Constructors

A constructor with no argument is known as default constructor in java. Refer thLets see a simple example first:

class employee{
   /*This is my default constructor. A constructor does
    * not have a return type and it's name
    * should exactly same as class name
    */
   employee(){
      System.out.println("Default constructor");
   }
   public void mymethod()
   {
      System.out.println("Void method of the class");
   }
   public static void main(String args[]){
	/* Creating object of class using default constructor
         * (new employee()) so default constructor would be 
         * invoked 
         */
	employee obj = new employee();
	obj.mymethod();
   }
}
Output:

Default constructor
Void method of the class

parameterized constructor.

A constructor with arguments is known as parameterized constructor.Consider the below code: Here I have declared three constructors: one is default and two are parameterized. As you can see when we created the objects of class, these constructor got invoked, based on the parameters (or arguments) we provided during object creation.

class Employe{
   //Default constructor
   Employee(){
      System.out.println("Default constructor");
   }
   /* Parameterized constructor with 
    * two integer arguments
    */
   Example(int i, int j){
      System.out.print("parameterized constructor");
      System.out.println(" with Two parameters");
   }
   /* Parameterized constructor with 
    * three integer arguments
    */
   Employee(int i, int j, int k){
      System.out.print("parameterized constructor");
      System.out.println(" with Three parameters");
   }
   public static void main(String args[]){
      //This will invoke default constructor
      Employee obj = new Employee();
      /* This will invoke the constructor 
       * with two arguments
       */
      Employee obj2 = new Employee(12, 12);
      /* This will invoke the constructor 
       * with three arguments
       */
      Employee obj3 = new Employee(1, 2, 13);		
   }
}
Output:

Default constructor
parameterized constructor with Two parameters
parameterized constructor with Three parameters

private constructor

The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time. We will see in the below example how to use private constructor for limiting the number of objects for a singleton class.

public class Example {
   //Static Class Reference
   private static Example obj=null;
   private Example(){
      /*Private Constructor will prevent 
       * the instantiation of this class directly*/
   }
   public static Example objectCreationMethod(){
	/*This logic will ensure that no more than
	 * one object can be created at a time */
	if(obj==null){
	    obj= new Example();
	}
        return obj;
   }
   public void display(){
	System.out.println("Example");
   }
   public static void main(String args[]){
	//Object cannot be created directly due to private constructor 
        //This way it is forced to create object via our method where
        //we have logic for only one object creation
	Example myobject= Example.objectCreationMethod();
	myobject.display();
   }
}
Output:
 Example
 

Java static constructor.Is it really Possible to have them in Java?

Have you heard of static constructor in Java? I guess yes but the fact is that they are not allowed in Java. A constructor can not be static in Java. Before I explain the reason let’s have a look at the below piece of code:


Why java doesnot support static constructor?

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.

class Employee1
{
     public Employee1()
     {
         /*Constructor of this class*/
         System.out.println("Employee1");
     }
}
public class Employee2 extends Employee1
{
     public Employee2()
     {
          /*By default this() is hidden here */
          System.out.println("Employee2");
     }
     public void display()
     {
          System.out.println("Employee Details");
     }
     public static void main(String args[])
     {
          Employee2 obj = new Employee2();
          obj.display();
     }
}
Output:
Employee1
Employee2
Employee Details

Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in java but there scope is within the class only.Like constructors method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.If you don’t define any constructor within the class, compiler will do it for you and it will create a no-arg (default) constructor for you.

Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.Constructors can not be inherited.If Super class doesn’t have a no-arg(default) constructor then compiler would not define a default one in child class as it does in normal scenario.

Interfaces do not have constructors.Abstract can have constructors and these will get invoked when a class, which implements interface, gets instantiated. (i.e. object creation of concrete class).A constructor can also invoke another constructor of the same class – By using this(). If you wanna invoke a arg-constructor then give something like: this(parameter list).

News Walls


Copyrights © 2016. All Rights Reserved to Learn Computers Home, India. //Site Designed.