new
keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences. - Constructor name is class name. A constructors must have the same name as the class its in.
- Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
- Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
- Differences between methods and constructors.
-
this(...) - Calls another constructor in same class.
Use super to call a constructor in a parent class.
- Need for explicit call to base class constructor using super in java
- Default field initialization in java
- Explicit or direct field initialization in java. Also see cpp vs java on direct field initialization here.
- Naming convention in java for constructors
- Initialization block in java
- Order of initialization in java
- Static initialization in java
- Object destruction and finalize method in java
If you don't set a field explicitly in a constructor, it is automatically set to a default value: numbers to 0, Booleans to false, and object references to null. But it is considered poor programming practice to rely on this. Certainly, it makes it harder for someone to understand your code if fields are being initialized invisibly. See here for more.
No comments:
Post a Comment