+2 votes
168 views
What is a constructor in a class ,in Java programming ?

What is the importance & use of that ?
asked Dec 30, 2015 in Computer Science - IT by peliant (217 points) | 168 views

1 Answer

+4 votes
Best answer

Hai , I will explain some points about constructor…

What is constructor???

  •  Constructor is a special member function…..

(Member function--- block of statements which perform some operations and return the result if need…)

Rules for constructor…

  • Constructor name is same as class name (So only called special member function)
  • Constructor can be overloaded
  • Constructor should not return the value..( Because every function return some value)

Importance and use of constructor…

1) Constructor can be called automatically when object of the class created..in normal methods we want to call the methods explicitly.

Example..

Member function

Class test

{

Void get()    //function

{

}

Public static void main(String args[])

{

test t=new test();

t.get() ; //explicit call

}

Constructor

Class test

{

test() //constructor

{

}

Public static void main(String args[])

{

test t=new test(); //constructor called automatically

}

2) We can apply some special purpose to function using abstract, final, static keywords.but in

Constructor cannot be use abstract, final, static keywords.

> when we are using abstract keyword in front of methods(abstract void get())..this methods must be explain in derived class..

-> when we are using static keyword in front of methods(static void get()..we can call this method without creating object..

-> we can not apply abstract,static keyword to constructor.

Thank you

answered Dec 30, 2015 by gypsiii (353 points)
edited May 6, 2016 by gypsiii
+1 good explanation for even beginners !
answer good but not able to understand :
2) We can apply some special purpose to function using abstract, final, static keywords.but in

Constructor cannot be use abstract, final, static keywords.

Can you please explain the same..or just edit the answer
tanq for your comment..

-> when we are using abstract keyword in front of methods(abstract void get())..this methods must be explain in derived class..

-> when we are using static keyword in front of methods(static void get()..we can call this method without creating object..

-> we can not apply abstract,static keyword to constructos.
add comment in answer so that others can see them with your answer