Do you know what are the Interface hidden rules ?

Interface:
Just simple definition  is collection of public static final variable and public abstract  methods.

Let me write one example:

interface A{
 int a= 10;
 void show();
 }

Is this example telling you what exactly I give  in the definition ?



Where is the public static final and  public abstract method declaration ?


Yes, above snippet is perfectly valid and my definition is also valid.

How come it is valid?

JVM internally adds the public static final for the variable and public abstract for the methods.

Interface implicitly itself an abstract.

For the  interface JVM adds the abstract  keyword and package level access(no-name) modifier.


So finally JVM convert the code like

abstract interface A{
 public static final int a= 10;
 public abstract void show();
}



Still you have doubt on this ?

Check with "javap", It tells you about the class/interface.

Interface rules:
  1.  Interface cannot be instantiated.

    Why?
      because method definition is not there.
      If A is interface we can't write like.
      A a = new A(); // Not valid"
    
    
  2. Interface can be inherited into a class by using implements keyword.
    interface A{
     int a= 10;
     void show();
     }
    class B implements A{
     void show(){
      // Some code
      }
    }
    
  3. Whenever interface is inherited into a class then all methods of an interface must be overridden in a subclass.
    or
    Subclass must be declared with abstract keyword otherwise compile time error occurs.

    interface A{
     int a= 10;
     void show();
     }
    abstract class B implements A{
        // Some code
    }
  4. Compile generate the .class file for interface also.

No comments:

Post a Comment