I am stuck at the below concept of initialization of java class and interface :
I read the following sentence in the below mentioned book :
An interface is initialized only because a non-constant field declared by the interface is used, never because a subinterface or class that implements the interface needs to be initialized.
But that isn't the case when we initialise any java class.Thus, initialization of a class requires prior initialization of all its superclasses, but not its superinterfaces.
Initialization of an interface does not require initialization of its superinterfaces.
My question is Why is this so ?
Any help would be greatly appreciated !
Thanks
PS : Book - "Inside the Java Virtual Machine" by Bill Venners (Chapter 7 - LifeTime of a class )
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.
A Class is initialized in Java when : 1) an instance of the class is created using either a new() keyword or using reflection using class. forName(), which may throw ClassNotFoundException in Java. 2) a static method of a class is invoked. 3) a static field of Class is assigned.
No you can not declare variable in interface. No, we can't declare variables, constructors, properties, and methods in the interface.
To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.
The only things you can declare in an interface are method signatures and constant fields. The latter can be initialized using constant values (i.e. string literals, integers, etc., possibly in some combination) or using non-constant values (i.e. method calls). Thus if an interface doesn't have any non-constant fields, no initialization is required -- everything is known at compile time. If there are non-constant fields that are used by the program, initialization code must be run to ensure those fields are assigned a value.
Hope that helps.
P.S.: That chapter is available online here if anyone wants to read it in full.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With