You have seen the keywords public and private. There are four access levels that can be applied to data fields and methods. The following table illustrates access to a field or method marked with the access modifier in the left column.

Classes can be default (no modifier) or public.

The access modifier keywords shown in this table are private , protected, and public.
When a keyword is absent, the default access modifier is applied.

The private keyword provides the greatest control over access to fields and methods. With private, a data field or method can be accessed only within the same Java class.

The public keyword provides the greatest access to fields and methods, making them accessible anywhere: in the class, package, , subclasses, and any other class.

The protected keyword is applied to keep access within the package and subclass. Fields and methods that use protected are said to be "subclass-friendly".

*Note: protected access is extended to subclasses that reside in a package different from the class that owns the protected features. As a result, protected fields or methods are actually accessible than those marked with default access control. You should use protected access when it is appropriate for a class's subclass but not unrelated classes.

Protected Access Control Example

In this example there are two classes in two packages. Class Foo is in the package demo, and declares the data field called result with a protected access modifier.

In the class Bar, which extends Foo, there is a method , reportSum , that adds the value of result to sum. The method then attempts to add the value of other to sum The field other is declared using the default modifier, and this generated the compiler error Why?

Answer: The field result, declared as a protected field , is available to all subclasses- even those in a different package. The filed other is declared as using default access and is only available to classes and subclasses declared in the same package.

This example is from the JavaAccessExample project.

Access Control: Good Practice

A good practice when working with fields is to make fields as inaccessible as possible, and provide clear intent for the use of fields through methods.

About Codingwelove

Recommended Posts × +


Post a Comment