-5

Why can I define only default and static methods inside a java interface,while other access modifiers like protected and public having much more privilege than default can't be used?

interface int1
{

     default void add(int a, int b)
    {

    }
    static void sub(int a, int b)
    {

    }

}
interface int1
{

    public void add(int a, int b)
    {

    }
    protected void sub(int a, int b)
    {

    }

}

--shows error message at compile time "Abstract methods do not specify a body"

  • 3
    You are confusing default access modifier (specify nothing in the signature) with default methods (provide _default_ keyword). – Kartik Jul 16 '19 at 07:01
  • Adding more into that, interfaces are used to abstractions of methods to be used in inherited classes. Therefore default methods are being implemented in interfaces while others are not. – Demotte Nov 19 '20 at 16:30

1 Answers1

1

The reason we have default methods in interfaces is to allow the developers to add new methods to the interfaces without affecting the classes that implements these interfaces. Here is link for complete article.

methamphetamine
  • 148
  • 1
  • 5