English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

can anbody explain me use of constructor in simple language.why class and constructor have same name.

2006-10-18 01:54:58 · 4 answers · asked by anu_reema_1983 1 in Computers & Internet Programming & Design

4 answers

For passing parameters( parameters i mean values that u want to use in the class) to a class we use constructor.

2006-10-18 02:01:22 · answer #1 · answered by Anonymous · 0 1

The constructor is a special method that is called when a class is instantiated for the first time (using the keyword 'new': Object o = new Object() ). Its typically used to initialise variables, or perform some actions before the class is ready to be used.

For example, say you have a class called Car, which contains the details of a particular model of car, and details of where this car can be bought and the price of it. In most cases, this information is typically stored in a database.

Sometimes its nice to pull in all this data straight from the database when the class is instantiated, so in the constructor we open a connection to the database,and query it for the information we need. So when the Car class is instantiated for the first time, all the information about it is immediately available.

Constructors have the same name as the class - in Java that's just a design decision. In other languages, like PHP the constructor method is called _constructor. In Java's case, perhaps they think by naming the method the same as the class it will stand apart from other methods, and so a programmer immediately knows this method is a constructor.

2006-10-18 04:26:32 · answer #2 · answered by Isofarro 3 · 0 0

You need constructors to allocate memory and initialise objects. They have the same name to make life easy.

Rawlyn.

2006-10-18 01:58:02 · answer #3 · answered by Anonymous · 0 0

You dont have to think too much about that. Its just a convention which has started from c++ itself. Thats it.

2006-10-18 05:45:27 · answer #4 · answered by Sudha P 2 · 0 0

fedest.com, questions and answers