Constructors : Initializing an Class Object in Java Programming
- Objects contain there own copy of Instance Variables.
- It is very difficult to initialize each and every instance variable of each and every object of Class.
- Java allows objects to initialize themselves when they are created. Automatic initialization is performed through the use of a constructor.
- A Constructor initializes an object as soon as object gets created.
- Constructor gets called automatically after creation of object and before completion of new Operator.
Some Rules of Using Constructor :
- Constructor Initializes an Object.
- Constructor cannot be called like methods.
- Constructors are called automatically as soon as object gets created.
- Constructor don’t have any return Type. (even Void)
- Constructor name is same as that of “Class Name“.
- Constructor can accept parameter.
Example : How Constructor Works ?
class Rectangle {
int length;
int breadth;
Rectangle()
{
length = 20;
breadth = 10;
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
}
}
Output :
C:Priteshjava>javac RectangleDemo.java
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
Explanation :
- new Operator will create an object.
- As soon as Object gets created it will call Constructor-
Rectangle() //This is Constructor
{
length = 20;
breadth = 10;
}
- In the above Constructor Instance Variables of Object r1 gets their own values.
- Thus Constructor Initializes an Object as soon as after creation.
- It will print Values initialized by Constructor –
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
0 comments:
Post a Comment
Let us know your responses and feedback