简体   繁体   中英

what happens to static block when we create multiple objects?

I have a class which has static members also non-static members like :

public class StaticClassObjectCreations {
    public static void doSomeThing() {
        // TODO implementations static
    }

    public void nonStaticMethod() {
        // TODO implementations for non static
    }

    public static void main(String[] args) {

        StaticClassObjectCreations obj = new StaticClassObjectCreations();
        StaticClassObjectCreations obj1 = new StaticClassObjectCreations();


    }

}

as we can see the number of object creation is not restricted and the non-static methods can be accessed with the help of objects created with new keyword.

the static methods or member variables will be also available for each instance and they can be accessed with out creating objects also.

now my question is : How the JVM maintains the instances for static block of code or in other words what happens to these static blocks when creating objects with new keyword.

thanks.

Static blocks/variable/methods are belong to Class, not instances of that Class. They will be initialized when the Class was loaded. There won't be any effect to these when you create instance of the Class. Even if you invoke a static member from an instance, compiler will replace instance with its Class.

Say you have classes A,B and C.

You have initialised a static array called "dataArray" in A.

You created an instance (object) of A in B and one in C.

The initialisation of these two objects will not affect "dataArray" in A since it is static. It will hold the same data for object in B and C. This is because static variables and methods are at class level, not object level.

Note: This is based on my experiments. If I am wrong, please respond.

If your question is about how the compiler treats a static method call using object reference,

public class StaticClassObjectCreations {

    public static void doSomeThing() {
        System.out.println("here");
    }
    public static void main(String[] args) {
        StaticClassObjectCreations obj = null;
        obj.doSomeThing();
        StaticClassObjectCreations.doSomeThing();
    }

}

compiler replaces object reference with its corresponding class to invoke the static method. Even if obj is null compiler wont give a null pointer because it doesnt need an object reference to invoke a static method.

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