The purpose of a constructor is initializing values for the fields, setting the initial state of the object. So what will happen if some fields or all fields were not initialized in the constructor?
Is it calling a default constructor provided by the JVM before the user defined constructor?
So, in this example, what would be output?
class Name{
int x;
boolean y;
Name(){
// no initialize
}
public static void main(){
Name n = new Name();
System.out.println(n.x + ", " + n.y);
}
}
You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.
I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly. Either way will work, and it's a matter of style, but I prefer constructors for member initialization.
You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.
Constructors for Initialization. Constructors for Initialization. A constructor must have the same name as the class. A constructor's function definition cannot return a value. No type, not even void, can be given at the start of the constructor's function prototype or in the function header.
Class-level fields (instance or static fields) get default values assigned to them. This means that if the constructor or instance (or static) initialization blocks don't explicitly initialize these fields, the default values will remain.
In your case:
class Name{
int x; //default value for int is 0
boolean y; //default value for boolean is false
In other words, your output should be 0, false
This question has details on the actual default values for primitive types. For Object data types, the default value is null
(see also the data types documentation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With