DEV Community

Cover image for The protected Data and Methods
Paul Ngugi
Paul Ngugi

Posted on

The protected Data and Methods

A protected member of a class can be accessed from a subclass. So far you have used the private and public keywords to specify whether data fields and methods can be accessed from outside of the class. Private members can be accessed only from inside of the class, and public members can be accessed from any other classes.

Often it is desirable to allow subclasses to access data fields or methods defined in the superclass, but not to allow non-subclasses to access these data fields and methods. To accomplish this, you can use the protected keyword. This way you can access protected data fields or methods in a superclass from its subclasses.

The modifiers private, protected, and public are known as visibility or accessibility modifiers because they specify how classes and class members are accessed. The visibility of these modifiers increases in this order:

Image description

Table below summarizes the accessibility of the members in a class.

Image description

Figure below illustrates how a public, protected, default, and private datum or method in class C1 can be accessed from a class C2 in the same package, from a subclass C3 in the same package, from a subclass C4 in a different package, and from a class C5 in a different package.

Image description

Use the private modifier to hide the members of the class completely so that they cannot be accessed directly from outside the class. Use no modifiers (the default) in order to allow the members of the class to be accessed directly from any class within the same package but not from other packages. Use the protected modifier to enable the members of the class to be accessed by the subclasses in any package or classes in the same package. Use the public modifier to enable the members of the class to be accessed by any class.

Your class can be used in two ways: (1) for creating instances of the class and (2) for defining subclasses by extending the class. Make the members private if they are not intended for use from outside the class. Make the members public if they are intended for the users of the class. Make the fields or methods protected if they are intended for the extenders of the class but not for the users of the class.

The private and protected modifiers can be used only for members of the class. The public modifier and the default modifier (i.e., no modifier) can be used on members of the class as well as on the class. A class with no modifier (i.e., not a public class) is not accessible by classes from other packages.

A subclass may override a protected method defined in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.

Top comments (0)