|
Constructors
A constructor is syntactically similar to a method that gets executed immediately when its class gets instantiated. A constructor has same name as that of it's class. The constructor is called by JVM as soon as the new operator is called.
Constructors can be useful when you want to perform some operations (like initialization) in the very begining.
An example is shown below:
class Human{
String name;
Human(){
name = "myName";
}
}
Whenever a command like Human h = new Human(); is issued, the constructor would be called immediately & will assign "myName" to h.name
Following are points worth noting:
- A constructor doesn't have a return type (not even void). This is because, constructor's return type is the class type itself.
- Even if don't create a constructor, Java creates default constructor.
- You can pass parameters to constructors. Parameters can either be primary variables, or full fledged objects.
- Constructors can also be overloaded just like ordinary methods.
- Calling super() actually calls parent class' constructor.
- In case of a hierarchy, constructors are called in order of derivation. For example, if there are 3 classes: grandParent, parent & child then first grandParent's constructor would be invoked, followed by parent's constructor, followed by child's constructor.
- A constructor can not be abstract.
|