Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Facts about Constructor with an example...............

Some facts that you should know about Constructor.....................


  • It has the same name as the classname.
  • It is used to initialize the object that means it is used to construct the object.
  • It does not have any return type.
  • It can have arguments.
  • The constructor without argument is called default constructor.
  • A class can have more than one constructor but they must be different from each other by  
     - Number of arguments or
     - Type of arguments or
     - Sequence of arguments
This concept is called constructor overloading.  

  • It is automatically called when an object is created.
Simple example to explain constructor in program.
___________________________________________


import java.io.*;
class cons
{
int a,b;
cons()//defulat constructer
{
a=10;
b=20;
System.out.println("default constructer");
}
cons(int p,int q)//parametrised constructer
{
a=p;
b=q;
System.out.println("parametrised constructer");
}
cons(int p)//one parametrised constructer
{
a=p;
b=25;
System.out.println("one parametrised constructer");
}
void show()
{
System.out.println("a = "+a);
System.out.println("b = "+b);
}

public static void main(String arg[])throws IOException
{
cons c1=new cons(); 
c1.show();
cons c2=new cons(10); 
c2.show();
cons c3=new cons(100,200); 
c3.show();
cons c4=new cons(); 
c4.show();
cons c5=new cons(); 
c5.show();
cons c6=new cons(1000,2000); 
c6.show();
cons c7=new cons(5000,10000); 
c7.show();
}
}


This post first appeared on LET's START CORE JAVA !, please read the originial post: here

Share the post

Facts about Constructor with an example...............

×

Subscribe to Let's Start Core Java !

Get updates delivered right to your inbox!

Thank you for your subscription

×