Documente Academic
Documente Profesional
Documente Cultură
qid=20090430013247AAPbbTA
Yahoo! My Yahoo! Mail More Make Y! My Homepage New User? Sign Up Sign In Help
Home > Computers & Internet > Programming & Design > Resolved Question
LOKESH
When a program creates an object with the new keyword, the java runtime allocates memory for the object. Before
transferring control to the program, the runtime initialises the object members, as per the instructions contained in the
programmer-defined constructor.
For example, if the class has an instance integer variable x, then the programmer can use the constructor to allocate
starting value for x at the time of object creation.
If the programmer does not provide a constructor, java itself provides a default constructor so that the instance variable x
is assigned with default values for the datatype ; in this case x is assigned with 0.
Further it is not necessary that the constructor should contain only statements for initialization statemnets for the object. It
can also contain any other user defined statements, which are informative or which provide proper environment for the
object to work properly - like opening of files, opening of database connections etc.
Constructor is called only one time during the life of the object, when it is created.
Constructor cannot be called by the programmer at will. It is used by the java runtime at the time of object creation.
A class can have more than one constructor that is, we can have several overloaded constructors. Programmer can
choose the appropriate constructor by giving proper arguments for the object's constructor at the time of creation.
1 of 2 6/20/2009 11:19 AM
Why we create object in constructor in java & how it is use? - Yahoo! A... http://in.answers.yahoo.com/question/index?qid=20090430013247AAPbbTA
You don't have to have a constructor, but java makes one if you don't.
class Cat {}
The java keyword 'new' makes the object by invoking the default constructor Cat(); new puts the Object onto the
computer heap and the human can reference the Object with his pointer --> kat.
The class file is just a template definition, not the Object. We can have more than one constructor and choose how the
Object is created.
class Cat {
private Color color;
public Cat(){}
public Cat( Color c ) {
this.color = c;
}
}
Cat kat2 = new Cat( Color.yellow );
Cat kat3 = new Cat();
2 months ago ( 2009-04-30 03:36:21 )
0% 0 Votes
deonejua...
Are you asking why you create a constructor or why do you create an object?
2 months ago ( 2009-04-30 01:45:18 )
0% 0 Votes
Tim D
Technology
http://karrox.info/
2 months ago ( 2009-04-30 01:36:37 )
0% 0 Votes
sony
2 of 2 6/20/2009 11:19 AM