A
A
Artem2021-09-06 21:16:19
Java
Artem, 2021-09-06 21:16:19

Why do uninitialized variables already have default values ​​when specifying a constructor?

Here is an example program where I define a constructor

class Test {
  int x, y;
  
  Test() {
    x = 3;
  }
}

class Main {
  public static void main(String[] args) {
    Test t = new Test();
    System.out.println(t.x + " " + t.y);
  }
}

And the output is: "3 0" The
book just told me that the default constructor is not provided if it is specified explicitly. The book is wrong || (she doesn't say something && I don't understand something)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-09-06
@Trame2771

Because int is a primitive type. Primitive types have a default value (they are not objects and cannot be null).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question