1

I know that the following code is wrong because the modifier public is missed in the header of the method m1() in class B. But i wonder "Why?!". Why the code causes a compile error if public is missed.

Thanks in advance.

interface A{
  void m1();
}
class B implements A{
  void m1(){
    System.out.println("m1");
  }
}
Hussein Eid
  • 209
  • 2
  • 9
  • Please edit your question to have a textual copy of the code, rather than a screenshot. Also, please add an appropriate tag for the language in question. – Joe Sewell Apr 28 '20 at 16:29
  • @JoeSewell Done – Hussein Eid Apr 28 '20 at 17:10
  • 1
    In interface `A`, the method `m1` is implicitly `public`. But for class `B` method `m1` is implicitly `package-private`. And the compiler won't let you assign weaker access to a method than what the interface allows for. This is a restriction based on the idea of design by contract. If the class can assign weaker access to the method, then the contract advertised by the interface is broken. – Matt Friedman Apr 28 '20 at 20:28

1 Answers1

0

By default methods have an access of package-private if no access modifier is specified, which means they are public to the package and class only. However interfaces require methods to be implemented by a class using an interface to be public.

See this stack overflow post for what default access modifiers are for classes and interfaces.

Eugene A.
  • 51
  • 1
  • 4