简体   繁体   中英

is there default constructor even if i mention constructor in class

public class Ex
{ 
  int a;   

  public Ex()   
  {
    System.out.println("a is "+a);   
  } 
}

output is:a is 0

where a gets initialized...

i know that default values for int is zero..my question is that where it gets initialied ..through default constructor ?(i heard that default constructor is created when we don't mention any constructor in the class)

No, there is no default constructor when you write a specific on. But fields get initialized before any constructor is called. After initialization of fields initializers ({.. some code .. } blocks)are run and finally the constructor is executed.

The reason why a has an initial value is written in the Java language specification (4.12.5) :

Each class variable, instance variable, or array component is initialized with a default value when it is created

a is an instance variable (a non static field) and so it has an initial value. The value itself is specified too:

For type int, the default value is zero, that is, 0.

It may be interesting to know that this is different for local variables (variables declared in a method body):

A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified by the compiler using the rules for definite assignment.

So if you read a local variable that has not been initialized or "set" in your code yet, the compiler will give an error.

To clear your head, if you had not declared a zero-argument constructor and your class had no constructor(s), java creates a default zero-argument constructor for you.

As for your primitive types, once declared, its initialized (if uninitialized) with default values before use.

§ JLS - 8.8.9 Default Constructor

In your code you have supplied constructor if you haven't then .

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided: If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments

在调用构造函数之前初始化基元

it occurs when Java allocates memory for a class. It fils all fields with default values;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM