Packages and Interfaces  «Prev  Next»

Lesson 5Controlling access in Java
ObjectiveControl access to Java Classes and class members.

Controlling Access in Java

Access Modifiers Significance
You control the access to a class using access modifiers, which define different levels of access for class members. For example, you might want the member variables for a class to only be accessible to derived classes. You must declare an access modifier before the type of a member variable, the return type of a method, or the definition of a class. Java supports four different access modifiers: public, protected, default, private. Some of these modifiers apply to classes, some to class members, and some to both:

public Classes, class members
protected Class members
default Classes, class members
private Class members


This series of images shows how the different access modifiers apply to a group of classes.
The frames demonstrate accessibility with respect to the Dog class:

 The public access modifier indicates that classes, member variables, and methods are freely accessible.
1)The public access modifier indicates that classes, member variables, and methods are freely accessible.

 The protected access modifier indicates that member variables and methods can only be accessed by derived classes and classes in the same package as the class.
2)The protected access modifier indicates that member variables and methods can only be accessed by derived classes and classes in the same package as the class.

 The default access modifier is used when none of the other access modifiers are explicitly declared.
3)The default access modifier is used when none of the other access modifiers are explicitly declared.

 The private access modifier indicates that member variables and methods are only accessible within the class in which they are defined. This means that no other class can access private member variables and methods.
4)The private access modifier indicates that member variables and methods are only accessible within the class in which they are defined. This means that no other class can access private member variables and methods.



Java Reference