Now, you are familiar with constructors in Java programming language. You know that an object is created by calling the constructor. However, when we have defined the classes, in many cases we have not defined the constructor. But, we have created the objects successfully.
We can create the objects of those classes in which constructors are not defined because JVM provides a default constructor if constructors are not defined. The default constructors do not receive any parameters.
You should know that the default constructor is provided if the class does not have any constructor. If a class contains any constructor, the default constructor can not be called. Still, if you want to call the default constructor, a constructor needs to be defined with a blank definition.
Let us try with examples.
ComplexNum.java
1
2
3
4
5
6
7
8
9
10
11
12
public class ComplexNum {
float x;
float y;
// constructor
public ComplexNum(int x, int y) {
this.x = x;
this.y = y;
}
}
The following code will not compile, because the default constructor is not available any more.
TestMain.java
1
2
3
4
5
6
7
8
public class TestMain {
public static void main(String[] args) {
ComplexNum cn = new ComplexNum();
}
}
But, if the ComplexNum class is defined as follows, the program will compile.
ComplexNum.java
1
2
3
4
5
6
public class ComplexNum {
float x;
float y;
}
TestMain.java
1
2
3
4
5
6
7
8
public class TestMain {
public static void main(String[] args) {
ComplexNum cn = new ComplexNum();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.