Sunday, May 12, 2013

Java Constructor Example

Java Constructor Example

In java the Objects are created by using the constructor.

Once we define a class in the java application, automatically the java compiler provides the

default constructor.

We can define parameterized constructors also depends on our requirement.

Example :

 Test test = new Test();
 class Test{
 }

In class Test we haven't defined any constructor, here the java compiler provides the constructor.

//default constructor in class Test
class Test{
  Test(){
 }
}

Constructor name must be same as class name.

//parameterized constructor

class Test{
  Test(int a,int b){
  }
}

Once we write any parameterized constructors in the class, the java compiler does not provide any
default constructor, so if we want default constructor we need explicitly define the default constructor
in the class.

To create an object for a class using parameterized constructor

Example : Test test = new Test(5,6);

Constructor is also similar to java methods, but there are the below differences

  • We must specify the return type for the method definition, where as for constructor there should not be any return type specified.
  • We can give any name for a method, but coming to constructor the constructor name and class name must be same.
 public class ConstructorExample {  
      ConstructorExample(){  
           System.out.println("default constructor");  
      }  
   ConstructorExample(int a){  
        System.out.println("one parameterized constructor "+a);  
      }  
   ConstructorExample(int a ,int b){  
        System.out.println("Two parameterized constructor "+a+ " "+b);  
      }  
      public static void main(String[] args) {  
           ConstructorExample c = new ConstructorExample();  
           ConstructorExample c1 = new ConstructorExample(1);  
           ConstructorExample c2 = new ConstructorExample(1,2);  
      }  
 }  

Output :

default constructor
one parameterized constructor 1
Two parameterized constructor 1 2

0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.