Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of Java - Class v/s Interface

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 )

like image 613
Saurabh Gokhale Avatar asked Jan 30 '11 16:01

Saurabh Gokhale


People also ask

Can you initialize an interface in Java?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.

What is Java class initialization?

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.

Can I initialize variable in interface?

No you can not declare variable in interface. No, we can't declare variables, constructors, properties, and methods in the interface.

How do you initialize a class variable in Java?

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.


1 Answers

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.

like image 187
Eric Giguere Avatar answered Sep 22 '22 06:09

Eric Giguere