9 Apply encapsulation

 

Exam objectives covered in this chapter

What you need to know

[8.1] Apply access modifiers

Application of access modifiers (public, protected, default, and private) to a class and its members. Determine the accessibility of code with these modifiers.

[8.2] Apply encapsulation principles to a class

Need for and benefits of encapsulation.

Definition of classes that correctly implement the encapsulation principle.

With encapsulation, you define variables and methods in a class and choose which ones to expose outside the class. This could help you prevent assignment of unwanted values to the members of your class. For example, for a class, say, BankAccount, you can enforce that it’s opening balance could never be negative. You can do that by restricting direct access to the field that stores this value and defining relevant business logic in the method that assigns value to it.

You can limit the accessibility of the members of your class or interface, by using the access modifiers – public, protected, default and private. In the OCP Java SE 11 Programmer I exam, you’ll be asked questions on how to apply the encapsulation principles to a class and the role of access modifiers in restricting access to members of a class or an interface. Given that information, this chapter will cover the following:

  • Access modifiers
  • Encapsulation principles

9.1      Access modifiers

[8.1] Apply access modifiers

9.1.1   Why do you need access modifiers

9.1.2   Public access modifier

9.1.3   Protected access modifier

9.1.4   Default access (package access)

9.1.5   Defining a class Book with default access

9.1.6   private access modifier

9.1.7   Access modifiers and Java entities

9.2      Apply encapsulation principles to a class

9.2.1   Need for encapsulation

9.2.2   Apply encapsulation

9.3      Passing objects and primitives to methods

9.3.1   Passing primitives to methods

9.3.2   Passing object references to methods

9.4      Summary

9.5      Sample exam questions

9.6      Answers to sample exam questions