+ 6
Default method access of an interface
Why is it that a default method declared in an interface when implemented by a class cannot be overridden when we use any other access modifier except public. Why can't it be accessed by default since both will have the same access.
8 Respostas
+ 6
Avinesh Interfaces define the public contract for interacting with an object from an external object without knowing the concrete class type. Only the interface type is required to be known in such cases.
Therefore, interfaces must always be implemented with a public accessor. It wouldn't make sense to define a private or protected interface for members that are not visible to external code.
+ 3
~ swim ~ Then is static also public inside the interface?
interface A{
static void show(){
System.out.println("hello");
}
}
+ 2
~ swim ~ I completely know what you just told me. Java 8 has introduced default and static methods and these are different from normal methods in the interfaces since default and static can have implementation within the interface. For eg-
interface A{
default void show(){
System.out.println("hello");
}
}
This interface when implemented by a class should allow us to override the method by using default, protected or public just like you mentioned above. But it doesn't work.
+ 2
~ swim ~ David Carroll
I am really sorry if I am asking something that is not making sense. I have spent close to two days on it already to understand.
+ 2
~ swim ~ Thanks a lot for really making it clear to me. I get it now.
David Carroll Thanks for that explanation.
+ 1
~ swim ~ David Carroll
First of all I do not understand how a method can be default and public at the same time. Ok for a second let us just keep it aside.
If static is also public inside the interface and if it cannot be overridden then I really need an explanation for this code because this thing works.
import java.util.*;
public class Program implements A
{
// Any access modifier works
private void show(){
System.out.println("hello");
}
public static void main(String[] args) {
Program obj = new Program();
obj.show();
}
}
interface A{
static void show(){
System.out.println("hi");
}
}
- 2
https://www.sololearn.com/Discuss/2072312/?ref=app