Skip to content

constructor and initialization

Keyhan Hadjari edited this page Sep 16, 2016 · 7 revisions

Constructor

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

Overloading

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

Initialization

  • 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"

Instance Initialization Block

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

Initialization Order

  1. static initialization blocks of super classes
  2. instance initialization blocks of super classes
  3. constructors of super classes
  4. static initialization blocks of the class
  5. instance initialization blocks of the class
  6. constructor of the class.

Variable Initialization

Local Variables

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

}

Instance and Class variables

  • 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

Clone this wiki locally