Java static

static properties/methods:
– can be referenced without creating an instance of the class.
– are shared by all members and exist for all runtime
– are allocated when the class is loaded
– can only be declared in outer classes (top level type) or in static nested classes

static variables are used to:
– to share data (be careful*, do not expose publicly )
– to define constants (static final variable means “constant”, usually used with public access as global constants e.g.
public static final int PI = 3.14;)

*Do not use static variables when multi-threading – several threads would override the same shared variable.

static methods are used:
– in utility classes (Utils.Math) – usually takes input parameters and return the result
– as factory methods
this classes should not be instantiated.

static method:
– is automatically final, so cannot be overridden, cannot be declared as abstract
– can always call/be called by static methods/fields (common scenario)
– can always called by instance methods
– can call instance fields/methods only via their own object reference:


class A {
    int i=0;
    void doSth(){}


    static void call() {
        A a = new A();
        a.doSth();


        // it is not possible to directly access
        // instance variables i or call directly
        // instance directly instance method doSth()

        // it won't compile:
        // doSth();
        // i=1;

        // static methods do not have access to 'this',
        // so it will also not compile:
        // this.doSth();
        // this.i=1;
    }
}

there is no polimorphism, e.g. Child extends Parent, both have print() method printing its class name:

Parent p = new Parent();
p.print(); // prints parent
Child c = new Child();
c.print(); // prints child
Parent pc = new Child();
pc.print(); // prints parent !!

for instance methods, the ‘child’ would be printed via polimorphism, the overridden method will not be used

inheritance – in the different sense:
Child extends Parent and only Parent class have print implementation, then:
Child.print()
will call internally Parent.print()

static initializing block

class ClassWithStaticBlock {
    static {
        System.out.println("Static block");
    }

    public ClassWithStaticBlock() {
        System.out.println("Constructor body");
    }
    public static void doSth() {
        System.out.println("Method body");
    }
}


public class InitializeByConstructor {
    public static void main(String[] args) {
        new ClassWithStaticBlock();
        new ClassWithStaticBlock();
    }
}

Result:
Static block
Constructor body
Constructor body

or

public class InitializeByAccessingStaticMethod {
    public static void main(String[] args) {
        ClassWithStaticBlock.doSth();
    }
}

Result:
Static block
Method body

Initialization by constructor makes sense when class contains non-static instance fields. In case of all static methods/fields, refer to them by class name (not by class instance).

initialization order

class BaseClass {


  static String myBaseStaticText=basesay("base static");


    String myBaseText = basesay("base local field");


    public BaseClass() {
        basesay("base constructor");
    }


    static String basesay(String text) {
        System.out.println(text);
        return text;
    }
}


public class InitializationTest extends BaseClass {


    static String myStaticText = say("static");


    String myText = say("local field");


    public InitializationTest() {
        say("constructor");
    }


    public static void main(String[] args) {
        new InitializationTest();
    }


    static String say(String text) {
        System.out.println(text);
        return text;
    }
}

Output:

base static
static
base local field
base constructor
local field
constructor

Static member (nested) class is instantiated independently from the enclosing outer class. There is no associated outer class object.
Non-static inner class objects always have an associated outer class object.

Static (and private/public/protected) keyword to declare a local field/class cannot be used inside the body of any method, only final and default access is permitted.

Anonymous classes are not allowed to declare static fields/methods. Anonymous classes when used in static context (inside static method or declaring&initializing static member variable), have only access to static member variables (not to instance member variables). Anonymous classes used in non-static context have access to both static and non-static member variables.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s