Encapsulation and visibility

Hiding an object's state: private, public, protected and package visibility, accessors and mutators, an invariant enforced by the mutator, and an internal reference not to hand out, in Java.

  • 27 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Understand

A few cards from the deck

  • Encapsulation: what is it?

    Show the answer

    The principle of bundling an object's state with the methods that handle it, exposing only those methods to the outside.

    The outside no longer touches the attributes: the class stays free to change its representation without breaking its users.

  • What does the compiler answer to this test program?

    ```java
    class Compte {
    private int solde;
    private void secret() { }
    }

    public class Main {
    public static void main(String[] args) {
    Compte c = new Compte();
    c.solde = 100;
    c.secret();
    }
    }
    `

    • Two errors has private access in Compte
    • None, Main and Compte are in the same file
    • A single error, on c.solde
    • Two warnings, the program runs
    Show the answer

    Two errors has private access in Compte

    private restricts access to the class itself, even if another class sits in the same file. Messages: solde has private access in Compte and secret() has private access in Compte.

  • To protect an object's state, its attributes are declared … and the methods offered to the outside ….

    Show the answer

    To protect an object's state, its attributes are declared private and the methods offered to the outside public.

    A private attribute can only be read and changed by the code of its own class.

  • Access modifier: what is it?

    Show the answer

    A keyword placed before a class member, which sets which parts of the program may use it.

    Java offers four levels: private, no keyword (package visibility), protected and public.

  • Why declare attributes private rather than public and add methods?

    • A private attribute takes less memory than a public attribute
    • Only its methods change the state: the class guarantees consistency
    • The compiler refuses to compile a class that has public attributes
    • Methods run faster than direct accesses to attributes
    Show the answer

    Only its methods change the state: the class guarantees consistency

    Visibility affects neither memory nor speed: it decides who may modify the state. That is what makes an invariant possible.