banner
Tenifs

Tenifs

雄关漫道真如铁,而今迈步从头越。
github
follow
zhihu
email

Access Modifiers in Java

In Java, public, private, and protected are access modifiers used to control the accessibility of classes, methods, and variables.

public#

  • Accessible from anywhere
  • Can create references to this member in any other class.
public class MyClass {
    public int myPublicVariable;
}

private#

  • Accessible only within the class that defines it.
  • Other classes cannot directly access this member.
public class MyClass {
    private int myPrivateVariable;
    
    private void myPrivateMethod() {
        // Available only in MyClass
    }
}

protected#

  • Accessible in other classes in the same package and all subclasses.
  • Suitable for members of classes that need to be inherited.
public class MyClass {
    protected int myProtectedVariable;
}

Default Access Modifier#

The default access modifier (no modifier used) allows access within the same package.

class MyClass {
    int myDefaultVariable; // Default access modifier
}

Summary#

  • public: Accessible from anywhere
  • private: Accessible only within the class
  • protected: Accessible in the same package and subclasses
  • Default: Accessible within the same package
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.