Skip to main content

3. Interface Implementation

 

Declaring an Interface

  • Interfaces are contracts for what a class can do, but they say nothing about the way in which the class must do it.
  • Interfaces can be implemented by any class, from any inheritance tree.
  • interface A{}
    interface B{}

    class Main implements A, B{}
  • An interface is like 100% abstract class, and is implicitly abstract whether we type the abstract modifier in the declaration or not.
  • abstract interface A{}
  • All interface methods are implicitly public and abstract.
  • interface A {
        void func1();

        public void func2();

        abstract void func3();

        public abstract void func4();

        abstract public void func5();
    }


  • All variables defined in an interface are implicitly public, static, and final. We need to initialize them while declaring and their values can't be changed.
  • interface A {
        int a = 10;
        public int b = 10;
        static int c = 10;
        final int d = 10;
        public static int e = 10;
        static final int f = 10;
        public final int g = 10;
        public static final int h = 10;
    }


  • An interface method can't be marked as strictfp and native.
  • If we mark a method as default or static or private, we need to define them in the interface. But a method marked as private can be used only by the interface.
  • interface A {
        default void func1() {}

        static void func2() {}

        private void func3() {}
    }


  • An interface cannot extend anything but can extend one or more other interfaces.
  • interface A{}

    interface B{}

    interface C extends A, B{}
  • An interface cannot implement another interface or class.
  • An class implementing an interface can itself be abstract.
  • An abstract implementing class does not have to implement the interface methods (but the first concrete subclass must).
  • interface A {
        void func();
    }

    abstract class B implements A {}

    class C extends B {
        @Override
        public void func() {
            // Method Body
        }
    }
  • A class can extend only one class (no multiple inheritance), but it can implement many interfaces.
  • interface A{}

    interface B{}

    class Main implements A, B{}

EXERCISE

interface A {
    int year = 2023;

    void func();

    default int getYear() {
        return year;
    }
}

class Main implements A {

    @Override
    void func() {
        // Method body
    }
}

While overriding func() in Main class, if we write as

@Override
    public void func() {
        // Method body
    }

Now it will compile successfully.

Prev Next

Comments