Java Access Modifiers - A Method Available To Subclasses And Packages

What are the access modifiers that when used with this method make it available to all classes and subclasses in the package?

+2


source to share


4 answers


public

, protected

and the default modifier (which has no keyword). Everything except private

.

For example, suppose a package foo

has the following class:

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

      



Then the class foo.SecondClass

can call methods method1

, method2

and method3

, but not method4

.

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

+9


source


Everything except private (e.g. public, protected and the default modifier). See the following image. enter image description here



+2


source


The package access modifier is effectively the absence of a modifier. it is also referred to as the 'default' modifier. See here for details .

+1


source


Turns off protected

is actually less "protected" than it says nothing. Both are package-private by default and protected

allow access from within the package; protected

then adds visibility for subclasses outside of the package. He is more "protected" than public

.

+1


source







All Articles