sij
sij

Reputation: 306

Java Object Class, Constructor Chaining

Does this code get called for every object creation in Java, because every object extends Object ? Or does the JVM optimize it in some way to avoid the creation of some many Object's object in the heap.

What exactly happens in this method registerNatives().

package java.lang;  

public class Object {
  private static native void registerNatives();
  static {
    registerNatives();
  }

Upvotes: 1

Views: 204

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. The question here is not about Constructor chaining, but about static.

2. static variable will be initialized when the JVM loads the class, and JVM loads the class when the class is instantiated or any static method of that class is called.

3. So this static block will run every one time the JVM loads the class.

Upvotes: 0

Ahmad
Ahmad

Reputation: 2190

It does n't matter what registerNatives(). does. What does matter here is that you have enclosed it in static block. Static Blocks loaded and run when java Class Loader loads classes. So it is guaranteed to run exactly once per JVM.

Upvotes: 1

Autar
Autar

Reputation: 1589

Static blocks are only executed once, when the class is loaded.

As explained here or here, a block that will be executed every time an object of the class is initialized can also be defined : just remove the static keyword.

Upvotes: 2

Related Questions