Interface Methods and Interface variables

Interface Methods and Interface variables


                                       Interface Method 

every method present inside the interface is always public and abstract whether we are declaring or not.

interface interf{
 void m1();
}

why it is public and why it is abstract?

public-: to make the method public because it is available to every implementing class.

abstract-:implementation class is responsible for providing an implementation.


Hence inside the interface, the following method declaration are equal.

void m1();
public void m1();
abstract void m1();
public abstract void m1();

As every interface method is always public and abstract we can't declare an interface method with the following modifiers.


Which of the following method declaration are allowed inside the interface.

public void m1(){}                   //invalid
private void m1();                    //invalid
protected void m1();                //invalid
static void m1();                      // invalid
abstract public void m1();       //valid
public abstract native void m1(); //invalid


                                    Interface Variable


An interface can contain variables the main purpose of interface variables is to define requirement-level constants.

Every interface variable is always public static final whether we are declaring or not.

interface interf{
   public static  final int x=10;
}

  

Hence within the interface, the following variable declaration is equal.

int x=10;
public int x=10;
static int x=10;
public static int x=10;
public final int x=10;
static final int x=10;
public static final int x=10;

As every interface variable is always public static final we can't declare with the following modifiers.


For the interface variable compulsory we should perform initialization at the time of declaration otherwise we will get compile time error.

eg-:

interface interf{
   int x;
}
compile time error-: '=' symbole expected.


Inside the interface which of the following variable declaration are allowed.

int x;                                                    //invalid
private int x=10;                                  //invalid
protected int x=10;                              //invalid
transient int x=10;                               //invalid
volatile int x=10;                                //invalid
public static int x=10;                        //valid

Inside the implementation class, we can access interface variables but we can't modify values.

eg-:
interface interf{
    int x=10;
}
class Test implements interf{
  public static void main(String... args){
      x=333;
      System.out.print(x);  // compile time error-: can't assign value to final variable x
}
}
class Test implements interf{
  public static void main(String... args){
     int  x=333;
      System.out.print(x);   // output is-: 333
}
}