Java Access Modifiers: Public, Protected, Friendly and Private

The access to classes, constructors, methods and fields are regulated using access modifiers in Java, by signing the access Modifiers, a class or method can control what information or data would be exposed to other classes, the developer can take full advantage of java access modifiers to maximize re-usability and refectory.

Java provides a number of access modifiers to help you set the level of access you want set for classes, fields, methods and constructors in classes. A member has package or default accessibility when no accessibility modifier is specified.

  • Public variables – Visible to all classes.
  • Protected variables – Visible only to these classes which they belong, and any subclasses.
  • Friendly variables, the default –  No modifiers are needed, Visible to the package.
  • Private variables – Visible only to the class to which they belong.

More directly perceived through the senses:

Modifier    | Class | Package | Subclass | World

public      |  Y    |    Y    |    Y     |   Y

protected   |  Y    |    Y    |    Y     |   N

no modifier |  Y    |    Y    |    N     |   N

private     |  Y    |    N    |    N     |   N

For access modifiers public and private, its easy to understand hence we wouldn’t take examples on here, below is a code piece to demonstrate whats the difference between Access Modifiers Protected and Friendly.

package com.asjava;

public class TestOne {
      protected  static String protectedStr = "protected";
      static String friendlyStr = "friendly";
package com.asjava.ts;

import com.asjava.TestOne;

public class TestOneSon extends TestOne {
     public static void main(String[] args){
        //correct to use, class TestOneSon is subclass of TestOne
        //incorrect to use, friendly field is only visible to access in same package

Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *



  1. Severin

    Nice overview !