0

Consider the following protected class containing a public method.

package my.package;

class MyClass {
  public void myMethod() {
    // myMethod implementation
  }
}

Since MyClass is not marked as public, it therefore has protected access and thus is not accessible outside the package. However, its method myMethod is marked as public, signifying that it is accessible outside the class.

Since myMethod presumably cannot be accessed without accessing MyClass, why is it possible to mark myMethod as public? Is it because someone might extend MyClass from within the package, with a custom public class for use outside the package? For example:

package my.package;

public MyPublicClass extends MyClass {
  // MyPublicClass implementation
}

If so, is there any other use for a public method defined within a protected class?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
mherzl
  • 5,624
  • 6
  • 34
  • 75
  • *"Since MyClass is not marked as `public`, it therefore has `protected` and thus is not accessible outside the package"* — Well, the absence of an access modifier is called *package-private*, not *protected*. – MC Emperor Nov 18 '21 at 15:58
  • A default or protected class may not be referenced using that type name outside its package, but instances of such a class are definitely usable outside that package, and public methods can be called assuming they are defined in an interface implemented by that class or in a super-class. – Mark Rotteveel Nov 18 '21 at 16:33

0 Answers0