![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
The constructor is special member function which initializes object when it is created.
The constructor is needed when we want to assign default values if user has not given.
There are two types of constructor
Default Constructor is called when object of class is created. When there is no constructor has been defined explicitly (by user), then java calls default constructor automatically.
We can define only one default constructor in the class. Java initializes all instance variables to zero after creation.
Default Constructor is also known as Zero Parameterized Constructor because it does not take any argument
class classname { classname () // default constructor { // body of constructor function } }
Calculating area of Rectangle using Default constructor
class Rectangle { int length,width; Rectangle() { length = 12; width = 8; System.out.println("Values initialized"); } int area() { return length * width; } public static void main(String args[]) { Rectangle rect = new Rectangle(); System.out.println("Area of Rectangle : "+rect.area()); } }
Output
In above example we have created class names as Rectangle which is having Default Constructor as Rectangle(). This constructor is executed when the object is created.
The Constructor which accepts the parameters known as Parameterized Constructor.
Sometimes it necesary to pass arguments to constructor while creating an object. It can have any number of parameters separated by commas.
class className { className( parameter1, parameter2, ... parameterN) { body of Parameterized Constructor ... ... } }
Program to print the given string upto N times using Parameterized Constructor
class ParamDemo { int number; String message; ParamDemo(String msg, int num) { message = msg; number = ntimes; } void print() { for (int i=1;i<=number;i++) System.out.println("msg : "+message); } public static void main(String args[]) { ParamDemo pd = new ParamDemo("AndroidBerry", 7); pd.print(); } }
In above example we have printed the message AndroidBerry 7 times using Parameterized Constructor