Every Class has at least one constructor, which assign initial values to instance variables of the class. Name of the constructor is same as class name.
Every Class has at least one constructor, which assign initial values to instance variables of the class. Name of the constructor is same as class name. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Here we will discuss how a constructor is initialized and implemented in a class.
- Constructor is always called by new operator.
- Constructor are declared in the same way methods are declared only difference is that the constructor don't have any return type.
- Constructor can be overloaded provided they should have different arguments because JVM differentiates constructors on the basis of arguments passed in the constructor.
In the following example we have used two classes. First class we have used is "another" while second is the main class by the name Construct. In the Construct class two objectsare created by using the overloaded "another" Constructor by passing different arguments. Area of the rectangles are calculated by passing different values for the "another" constructor.
Example of Java Constructor:
class another{
int x,y;
another(int a, int b){
x = a;
y = b;
}
another(){
}
int area(){
int ar = x*y;
return(ar);
}
}
public class Construct{
public static void main(String[] args)
{
another b = new another();
b.x = 2;
b.y = 3;
System.out.println("Area of rectangle : " + b.area());
System.out.println("Value of y in another class : " + b.y);
another a = new another(1,1);
System.out.println("Area of rectangle : " + a.area());
System.out.println("Value of x in another class : " + a.x);
}
}
Output:
C:\chandan>javac Construct.java
C:\chandan>java Construct
Area of rectangle : 6
Value of x in another class : 3
Area of rectangle : 1
Value of x in another class : 1