REGISTER FREE to Receive Instant Job

Saturday, 1 November 2014

Constructor in Java

CONSTRUCTOR- It is special member of a class that has following characteristic:-
  • It has the same name as of its class.
  • It does not have an explicit return type.
  • It is implicitly invoked just after an object is created.
  • It is used to initialize data members of objects.
 Rectangle r = new Rectangle();

  • Rectangle r;                        //Reference Variable created
  • r = new Rectangle(); //memory allocation for object
  • r.Rectangle(5, 4);             //Constructor is invoked

Note: If a class doesn’t contain any constructor then default constructor is provided by the compiler at the time of compilation but if a class contains any parameterized constructor and there is an object of the class which requires default constructor for its initialization then default constructor need to be defined in the class. In this case, it won’t be provided by the compiler.


public class ExampleofConstructor{
/*Define using variables in program     */
int emp_id;
String emp_name;

/*Constructor two types: default and parameterize*/

/*Define Here Default Constructor*/

ExampleofConstructor(){ }

/*Define Here Parameterize Constructor*/

ExampleofConstructor(int i,String n){emp_id=i;emp_name=n;} // define two parameter: emp_id and emp_name

/*define show method to display output after calling by parameterize constructor and default constructor*/

void show(){System.out.println(emp_id+"-"+emp_name);}

public static void main(String arg[]){
ExampleofConstructor emp1=new ExampleofConstructor(001,"Anuj"); //Parameterize Constructor passing two value;

ExampleofConstructor emp2=new ExampleofConstructor(); //Default Constructor;

Watch Video:

1 comment:

Popular Posts

Powered by Blogger.

About Me

My photo

JobsAcid is a 'job search engine' to provide finding a job on the internet easier for the user. It has designed as huge selection of job offerings on the same search engine.