-
Notifications
You must be signed in to change notification settings - Fork 0
constructor and initialization
Keyhan Hadjari edited this page Sep 16, 2016
·
7 revisions
- A constructor must have the same name as the class, hence a is not a constructor.
- It must not return any value, hence c is not correct. A constructor cannot be declared abstract or final.
- Constructor parameter cannot be void.
- After a constructor call is finished, all the final constants has been initialized and cannot be changed.
public class Person{
public Person(String name, int age) { //1
this.name = name;
this.age = age;
}
public Person(String name) {
this(name,0); //calling constructor at 1
}
}- The initial value of an instance variable of type String that is not explicitly initialized in the program is null
- The initial value of a local variable of type String that is not explicitly initialized and which is defined in a member function of a class must be explicitly assigned.
- A Boolean is set to false if initialized with no particular value.
- Preferred String initialization String str = "Welcome to Java Programming"
- Is used to initialize the instance data member. It run each time when object of the class is created.
- Instance itialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.
- static initialization blocks of super classes
- instance initialization blocks of super classes
- constructors of super classes
- static initialization blocks of the class
- instance initialization blocks of the class
- constructor of the class.
Local variables are defined within a method. They must be initialized before use. Using it uninitialized will give you the compilation error "variable x might not hve been initialized".
void foo(int bar) { // bar and x are local variables
short x; // uninitialized
}- Class variables or class fields are always static, which makes them shared for all instances of the class.
- Instance variables or instance fields are not static and unique for each instance of a class.
Both Instance and class variables are initialized with default a value if no value has been given to them. Below is a table describing these default values:
public class Foo {
static int bar; // class variable, set default to 0
short x; // instance variable, set default to 0
}| Type | Default Value |
|---|---|
| int,short,long,byte | 0 |
| float, double | 0.0 |
| char | '\u0000' |
| object references | null |