Interface Methods and Interface variables

Interface Method

Every method present inside an interface is always public and abstract, whether we declare it or not.

interface Interf {
    void m1();
}

Why public?
Because interface methods must be accessible to every implementing class.

Why abstract?
Because interfaces only define behavior, and the implementation is provided by the implementing class.

Important Point: Interface acts like a contract. Any class implementing it must provide implementation for all abstract methods.

Equivalent Declarations:

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

Extra Explanation: Even if you don’t write public and abstract, the compiler automatically adds them.

Invalid Method Declarations:

public void m1() {}        // ❌ Method body not allowed
private void m1();        // ❌ Not allowed
protected void m1();      // ❌ Not allowed
static void m1();         // ❌ (in older versions)
public abstract native void m1(); // ❌ Invalid combination
abstract public void m1(); // ✔ Valid

Extra Note: Interface methods cannot be private or protected because they must be visible to implementing classes.


Interface Variable

An interface can contain variables. These variables are used to define constants.

Every interface variable is always public static final, whether we declare it or not.

interface Interf {
    int x = 10;
}

Explanation:

  • public → Accessible everywhere
  • static → Belongs to interface, not object
  • final → Value cannot be changed

Equivalent Declarations:

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;

Important Rule: Interface variables must be initialized at the time of declaration.

interface Interf {
    int x;   // ❌ Compile-time error
}

Error: '=' expected

Extra Explanation: Since variables are final, we cannot modify them after initialization.

interface Interf {
    int x = 10;
}

class Test implements Interf {
    public static void main(String[] args) {
        x = 333;   // ❌ Error
    }
}

Error: Cannot assign value to final variable

Correct Approach:

class Test implements Interf {
    public static void main(String[] args) {
        int x = 333;
        System.out.println(x); // ✔ Output: 333
    }
}

0 Comments