Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if none or only some fields are initialized in a constructor [duplicate]

Tags:

java

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);
     }

 }
like image 478
Ishwar Mahawar Avatar asked Sep 20 '18 05:09

Ishwar Mahawar


People also ask

Do you have to initialize all variables in constructor?

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.

Why we always initialize instance variables in a constructor?

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.

Can we initialize without constructor?

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

What does it mean to initialize a constructor?

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.


1 Answers

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).

like image 107
ernest_k Avatar answered Oct 01 '22 22:10

ernest_k