Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What is a constructor in Java or OOP?

Status
Not open for further replies.

Namsu55

Technical User
Aug 14, 2006
8
0
0
GB
Hi, I have tried to understand what is a constructor, can some one give me an easy explanation, my understanding is that it is a type of method, inside a particular class, but can someone help me understand it better. Thank you.
 
When you instantiate a new object, a specific constructor is called once and only once, for each instantiation of said class.
You should only use a constructor to initialise (typically) private member variables that are relied upon by methods contained within that object.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Think of it like buying furniture from IKEA. If they sold you all the pieces for a desk, but they aren't actually assembled into a desk yet, that would be like an object without a constructor. An object with a constructor would be if you buy a fully assembled desk and there's no assembly required on your part. ;-)
Now that's the default constructor (i.e. without passing any arguments). You can also have constructors where you pass some parameters to it so you can customize how you want that object to look.
 
A constructor isn't a method.
It doesn't have a return statement, and you may not call a constructor for an existing Object.
You invoke the constructor by calling 'new' which is another difference to methods.

The constructor creates a new Object, and returns a reference to that object.

don't visit my homepage:
 
Or put another way, a constructor is an operator (in the mathematical sense) whose domain is a class (which is abstract in the mathematical sense although in Java, "abstract" means something more particular) and whose range is objects.

_________________
Bob Rashkin
 
Constructtor has same name as a calss name with no return statement.
It is called by new operator
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top