Java Constructor
Java Constructor
The constructor name must match the class name, and it cannot have a return type (like void).
All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.
Example1:
public class Myclass {
int x;
public Myclass() {
x = 5;
Myclass myObj = new Myclass(); // Create an object of class Myclass (This will call the constructor)
}}
Constructor Parameters:
Constructors can also take parameters, which are used to initialize attributes.
Example2:
public class Myclass {
int x;
public Myclass(int y) {
x = y;
Myclass myObj = new Myclass(5); // Create an object of class Myclass with parameter
}}
Example3:
public class Myclass {
int modelYear;
String modelName;
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
}}
More Examples:
}
void display()
{
[Link]("Class A x is :"+x);
}
}
class B
{
int x;
B(int y)
{
x=y;
}
void display()
{
[Link]("Class B x is :"+x);
}
}
public class ConstructorEx1 {
public static void main(String[] args) {
A ob=new A(5);
B ob1=new B(6);
[Link]();
[Link]();
}
}
Ex2: (Use of this)
package DSA;
class AA
{
int x;
AA(int x)
{
this.x=x;
}
void display()
{
[Link]("Class AA x is :"+x);
}
}
class BB
{
int x;
BB(int x)
{
this.x=x;
}
void display()
{
[Link]("Class BB x is :"+x);
}
}
public class ConstructorEx2 {
public static void main(String[] args) {
AA ob=new AA(5);
BB ob1=new BB(6);
[Link]();
[Link]();
}
}
Constructor Overloading in Java
Java supports Constructor Overloading in addition to overloading methods.
In Java, overloaded constructor is called based on the parameters specified when a new is executed.
Example:
class Box {
double width, height, depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// Driver code
public class Test { Output:
public static void main(String args[])
{ Volume of mybox1 is 3000.0
// create boxes using the various
// constructors Volume of mybox2 is 0.0
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(); Volume of mycube is 343.0
Box mycube = new Box(7);
double vol;