Java.Core.Define the concept of “interface.” What modifiers do interface fields and methods have by default?

Definition of an Interface

In Java, an interface is a reference type that defines a contract that classes can implement. It consists of abstract methods (which must be implemented by the implementing class) and static or default methods (which can have a body). Interfaces are used to achieve abstraction and multiple inheritance in Java.

Default Modifiers in an Interface

1. Fields in an Interface

  • All fields in an interface are implicitly public, static, and final.
  • Example:
interface MyInterface {
    int VALUE = 10; // This is implicitly public, static, and final
}

Equivalent to:

interface MyInterface {
    public static final int VALUE = 10;
}

2. Methods in an Interface

  • By default, all methods in an interface are implicitly public and abstract (unless they are static or default).
  • Example:
interface MyInterface {
    void doSomething(); // This is implicitly public and abstract
}

Equivalent to:

interface MyInterface {
    public abstract void doSomething();
}

3. default and static Methods

  • Since Java 8, interfaces can have methods with bodies:
    • default methods: Provide a default implementation for methods in the interface.
    • static methods: Can be called directly from the interface without an instance.
    Example:
interface MyInterface {
    default void defaultMethod() {
        System.out.println("This is a default method.");
    }

    static void staticMethod() {
        System.out.println("This is a static method.");
    }
}

Summary

FeatureDefault Modifier(s)
Fieldspublic static final
Methodspublic abstract (unless default or static)
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.