The access modifiers of methods and variables of a java class

In this article I explain how to set the visibility of methods and instance variables, ie those variables declared outside of any method (the variables declared within a method are called local variables and they are visible in the method only).

The access modifiers of methods and variables in java are:

  • public
  • private
  • protected

that define 4 types of visibility, being the fourth got with the absence of an access modifier (default).
The class must be visible as explained in this post, if it is visible the access modifiers applied to methods and variables define the visibility.

If the class is not declared as public (default), all its methods and variables are visible to classes in the same package except for those declared private.
If the class is not declared as public (default), all its methods and variables are hidden from the classes of other packages.
Look carefully the following code in which the class B access to the methods of the class A from the same or a different package.

If the class is declared as public, all its methods and variables are visible to classes in the same package except for those declared private.
If the class is declared as public, all its methods and variables are visible to classes in other packages except those declared private (default), and protected in the event of a subclass.
Look carefully the following code in which the class B access to the methods of the public class A from the same or a different package.

We can summarize with the following table:

  class B
same package
class B extends A
same package
class B
different package
class B extends A
different package
(default) class A public: yes
private: no
protected: yes
(default): yes
hidden
public class A public: yes
private: no
protected: no
(default): no
public: yes
private: no
protected: yes
(default): no

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.