Default method access of an interface | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

16th Nov 2019, 6:53 AM
Avinesh
Avinesh - avatar
8 Answers
+ 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.
16th Nov 2019, 9:48 AM
David Carroll
David Carroll - avatar
+ 3
~ swim ~ Then is static also public inside the interface? interface A{ static void show(){ System.out.println("hello"); } }
16th Nov 2019, 9:21 AM
Avinesh
Avinesh - avatar
+ 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.
16th Nov 2019, 9:01 AM
Avinesh
Avinesh - avatar
+ 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.
16th Nov 2019, 10:06 AM
Avinesh
Avinesh - avatar
+ 2
~ swim ~ Thanks a lot for really making it clear to me. I get it now. David Carroll Thanks for that explanation.
16th Nov 2019, 10:12 AM
Avinesh
Avinesh - avatar
+ 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"); } }
16th Nov 2019, 9:58 AM
Avinesh
Avinesh - avatar
17th Nov 2019, 7:00 PM
Ananta Khare
Ananta Khare - avatar
- 2
https://www.sololearn.com/Discuss/2072312/?ref=app
17th Nov 2019, 5:27 PM
Abdul Wahab Chattha
Abdul Wahab Chattha - avatar