Java Basics  «Prev  Next»

Lesson 6Variable and method Access control in Java
ObjectiveIdentify variables and methods to access based on their keywords.

Java Variable and Method Access Control

  1. Identify which variables and methods you can access based on their keywords.
  2. Use keywords for variables and methods that restrict access.

Let's learn about two factors that affect how and when you can access classes, methods, and variables:
  1. Which access control package they are in
  2. What keywords (access control inheritance) have been assigned to them

Classes are grouped into Packages

Based on the information retrieved the Java API HTML files, all Java's classes are grouped into packages. You can group your own classes into packages. All our Java programs will reside in the same package, which is what occurs by default.
  • Relating to packages: Members of a class (its variables and methods) can be accessed freely by any other class within the same package. If the member is declared as private, then it cannot be accessed freely. If you would like to make the class members accessible to code outside the package in which it is defined, you must start by declaring the class to be public.
    public class VisibleToAll {
      String Visible = new String();
    }
    

You can declare the members you want to access outside that package as public. If you look through Java's API, you will notice that the majority of Java's
  1. classes,
  2. methods, and
  3. variables

are declared as public, so that code outside the packages in which these classes, methods, and variables are defined can also access and use them.


Java Access Modifiers

When you declare an object type in Java (let us stick to class because it is the only one mentioned so far), you can configure who should be able to use it. Access modifiers specify access to classes, and in this case, we say that they are used at the top-level. They can also specify access to class members, and in this case, they are used at member-level. At the top-level there are only two access modifiers that can be used: 1) public and 2) none.A top-level class that is declared public must be defined in a Java file with the same name. So, the following class is defined in a file named Base.java stored under the com.
package com.javadeploy.java.module1;

public class Base {
  // define your member variables and methods
}

The contents of the class are not depicted for the moment and have been replaced with a comment. A public class is visible to all classes anywhere and a different class in a different package, can create an object of this type, like in the following sample code:
package com.javadeploy.java.module1;

public class Main {
 public static void main(String... args) {
   // creating an object of type Base
   Base base = new Base();
 }
}

For now, remember that a public class is visible to all classes everywhere.


Access Control for Inheritance using Java

Once you can access a class, what are the controls you can place on its members?
You can restrict access to instance variables and methods from one class to another. And it is not always the case that a subclass can access the methods and variables of its superclass. Sometimes you want to keep certain data or behavior hidden even from subclasses.
  • private keyword in Java: For example, a class called Vehicle, acting as a superclass for all Car, Bus, and Truck classes, might maintain the Vehicle's VIN (Vehicle Identification Number) and want to keep it private. The Vehicle class can use a keyword to accomplish this, called naturally enough private.
    class Vehicle {
      private char[] vin = new char[25]; 
    }
    

    The only way to access this vin variable outside of the Vehicle class is for the Vehicle class to provide a method that accesses it. For example, the Vehicle class might provide a method that checks its private VIN with one passed into a method:
    class Vehicle {
      private char[] vin = new char[25];
      booleancompareVIN(char[] comparisonVIN) {
      for(int i = 0; i < 25; i++){
        if (vin[i] != comparisonVIN[i]){
         returnfalse; 
        }
        returntrue; 
      }// end -for}
    

    Since there is no way for any other class to access this variable, we also need a way for the Vehicle class to initialize it. We might accomplish this by defining a constructor that takes a char array as an argument and initializes vin appropriately.
    If we made a subclass, perhaps like this:
    classCar extends Vehicle { 
      // code goes here
    }
    

    there is no way we could include a method for Car that would access the private variable named vin in the Vehicle class.
  • protected: We can also declare a member (a variable or method) to be protected.
    A protected variable or method is available only to that class and its subclasses (or to classes defined in the same package as the class defining the protected member). Classes in other packages that are not subclasses cannot access protected members. With the example just given, if we had used protected instead of private, as in:
    protected char[] vin = new char[25]; 
    

    then Car could have accessed vin directly. However, other classes in other packages would not be able to access vin.
  • public: At the other extreme, if we declared vin using the keyword public, any class could access vin, in this or any other package.
    default Access: The default, without any keywords, makes a member accessible only within the package that defines it.


As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute which is access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a well-designed set of methods, you can prevent the misuse of that data. Thus, when correctly implemented, a class creates a "black box" which may be used, but the inner workings of which are not open to be altered. However, the classes that were presented earlier do not completely meet this goal. For example, consider the Stack class. While it is true that the methods
  1. push( ) and
  2. pop( )
do provide a controlled interface to the stack, this interface is not enforced. That is, it is possible for another part of the program to bypass these methods and access the stack directly. Of course, in the wrong hands, this could lead to trouble. In this section, you will be introduced to the mechanism by which you can precisely control access to the various members of a class.

Examine the definitions of the classes House and Book in the following code.
package building;
class House {}

package library;
class Book {}

With the current class definitions, the class House cannot access the class Book.
Question: Can you make the necessary changes (in terms of the access modifiers) to make the class Book accessible to the class House?
You know that a top-level class can be defined only using the
  1. public or
  2. default access modifiers.
If you declare the class Book using the access modifier public, it will be accessible outside the package in which it is defined.
Note: A top-level class is a class that is not defined within any other class. A class that is defined within another class is called a 1) nested or 2) inner class. Nested and inner classes are not on the OCA Java SE 7 Programmer I exam.
Access modifiers control the accessibility of a class or an interface, including its members (methods and variables), by other classes and interfaces. For example, you cannot access the private variables and methods of another class. By using the appropriate access modifiers, you can limit access to your class or interface, and their members, by other classes and interfaces.


Access Control - Quiz

The following discusses access control.
Access Control - Quiz

SEMrush Software