Can anybody please tell me what the Constructors are used for exactly in Java?
What could be the ideal condition for using the constructors in an application?
Thanks, david
Can anybody please tell me what the Constructors are used for exactly in Java?
What could be the ideal condition for using the constructors in an application?
Thanks, david
Constructors are very useful for initializing instance variables. For instance, say you have a User class, and you would like to initialize the userName property whenever you create a new instance:
Class User
{
String userName;
public User (String name)
{
userName = name;
}
}
User oUser = new User("Mike");
Note - When you write your own constructor, java doesn't provide a default constructor
They are used to initialize objects. You should take a look at some good OO tutorial. Here's one: http://www.javaworld.com/javaworld/jw-04-2001/jw-0406-java101.html. Specifically, this page: http://www.javaworld.com/javaworld/jw-04-2001/jw-0406-java101.html
Constructors are used to initialize the class fields when the new object of the class is made.
Moreover in the singleton design pattern you will see the more uses of the constructor where the single instance of the class is made in the constructor being the constructor private, so that no other object of the class can be made.
A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.
They have no return type, not even void. This is because the implicit return type of a class constructor is the class type itself.
Class ConstructorExample{
String agentJamesBond;
ConstructorExample(String number)
{
agentJamesBond= number;
}
//various methods(member of class ConstructorExample) which uses instance variable agentJamesBond.
}
//at the point of creation of the constructor
ConstructorExample xyz= new ConstructorExample("007");
They are created by default, if not defined explicitly.
It's job is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.
A constructor is creating an instance of a class. Note, that what's created is the object, not an instance of an object. There might be some initialization in a constructor, but the main functionality of all the constructors is: creating the object.
new opcode creates the object, the constructor initializes it. When you say new Foo(), the resulting bytecode performs these two steps in sequence. See java.sun.com/docs/books/jvms/second_edition/html/…