Search code examples
javaaccess-modifiers

Java access modifiers - method available to subclasses and package


Which access modifiers which when used with the method makes it available to all the class and subclasses within a package?


Solution

  • public, protected and the default modifier (which doesn't have a keyword). Everything except private.

    For example, suppose the package foo has the following class:

    public class MyClass {
       public void method1() { };
       protected void method2() { };
       void method3() { };
       private void method4() { };
    }
    

    Then a class foo.SecondClass could call the methods method1, method2 and method3, but not method4.

    See the Java tutorial for a useful table of what each modifier allows.