Sunday 26 October 2014

Constructor in java

Java constructors are the methods which are used to initialize objects. Constructor has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. 

Example of Constructor:

public class A
{
 public A()  // constructor method
 {
 
 }
}

Types of Constructor 

1. Default Constructor.
2. Parameterized Constructor.

1. Default Constructor.

If Constructor method has no argument then its known as the "default constructor".If we do not create constructor then compiler automatically crate "default constructor"

class A
{
 public A()  
 {
     System.out.println("Default Constructor called");
 }
}

public MainClass
{
 public static void main(String[] args)
 {
  A a=new A(); 
 }
}


OUTPUT
Default Constructor called

2. Parameterized Constructor.

If we pass arguments in constructors' method then it called as "parameterized constructor."
class A
{
 public A()  
 {
     System.out.println("Default Constructor called");
 }
 
 public A(int i)  
 {
     System.out.println("The value of i="+i);
 }
}

public MainClass
{
 public static void main(String[] args)
 {
  A a=new A(10); 
 }
}

OUTPUT
The value of i=10


Note :
Constructor never return a value.

Constructor Overloading:

Like other methods in java constructor can be overloaded we can create as many constructors in our class as desired. When we create object and pass the arguments appropriate constructor is called.

class A
{
 public A()  
 {
     System.out.println("Default Constructor called");
 }
 
 public A(int i)  
 {
     System.out.println("The value of i="+i);
 }
 public A(String arg)  
 {
     System.out.println("String Argument is="+arg);
 }
}

public MainClass
{
 public static void main(String[] args)
 {
  A a1=new A();
  A a2=new A(10);
  A a3=new A("Hello");
 }
}

OUTPUT
Default Constructor called
The value of i=10
String Argument is=Hello

Constructor chaining:

constructor can not inherited into subclass.But we can call super class constructor from subclass by "super() key word".when subclass object created subclass constructor invoked and by super keyword we can invoke super class constructor this is called "constructor chaining".

class A
{
 public A()  
 {
     System.out.println("A Constructor called");
 }
 
 public A(String arg)  
 {
     System.out.println("String Argument is="+arg);
 }
}
class B extends Argument
{
 public B()
 {
  super("Hello");
   System.out.println("B Constructor called");
 }
 public B(int i)
 {
  super();
  System.out.println("Argument is="+i);
 }
}
public MainClass
{
 public static void main(String[] args)
 {
  A a1=new A();
  B b1=new B();
  B b2=new B(20);
 }
}

OUTPUT
A Constructor called
String Argument is=Hello
B Constructor called
A Constructor called
Argument is=20

0 comments :

Post a Comment