In the constructor below, I have initialized only two of the variables, leaving some variables uninitialized explicitly.
As i have read, no argument constructor is created by the compiler if the constructor is provided by us.Then in such cases, since I have my own constructor so there is no default constructor which initializes variables p and q.
So, the logic should be if we try to access those uninitialized variables, then it should be a compile time error.However, the following code runs successfully.
The output is
5
10
0.0
0.0
How can we explain the output 0.0 and 0.0 since i have not declared them in the constructor ??
public class Rectangle {
int l, b;
double p, q;
public Rectangle(int x, int y) {
l = x;
b = y;
}
public static void main(String[] args) {
Rectangle obj1= new Rectangle(5,10);
System.out.println(obj1.l);
System.out.println(obj1.b);
System.out.println(obj1.p);
System.out.println(obj1.q);
}
}
Primitives are initialized to a default value, in this case, 0 for integers and 0.0 for floats or doubles. Objects are by default null, for example a String would be null.
The values you set in constructors are normally different from the default values, therefore the need for constructors.
The default initial values are a language feature, and does not require a constructor at all.
You read about the default values here : http://www.janeg.ca/scjp/lang/defaults.html
Remember though that the default values are only for CLASS members, not local variables. That difference is why you get compile errors for some values not being initialized.