'If interfaces are only allowed to be public, how does this work
This is the below code which compiles successfully
import java.util.*;
class Test
{
protected interface Yes
{
void show();
}
}
class Testing extends Test implements Test.Yes
{
public void show()
{
System.out.println("show method of interface");
}
}
class A
{
public static void main(String[] args)
{
Test.Yes obj;
Testing t = new Testing();
obj=t;
obj.show();
}
}
Solution 1:[1]
Your understanding is incorrect - see the Java Language Specification, section 9.1.1.
The access modifiers protected and private pertain only to member interfaces whose declarations are directly enclosed by a class declaration (ยง8.5.1).
Solution 2:[2]
Interfaces itself can have any visibility that classes can have. For top-level interfaces that's limited to public and package-private, for nested interfaces it can be anything.
Until Java 9, everything inside interfaces had to be public, and everything without an explicit visibility modifier automatically was. Java 9 made it possible to add private methods to interfaces, which can be called by default method implementations.
Note that protected inside interfaces is still not allowed, and package-private cannot be used because members without an explicit public or private modifier are automatically public.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | passer-by |
| Solution 2 |
