Unit 3 · OOP Concepts

3.3.3Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. List the four access levels in Java from most to least restrictive.
  2. Why should attributes usually be private?
  3. What is the difference between a static and a non-static attribute?
  4. What are the three uses of final?
Show answers
  1. private, default (no keyword, also called package-private), protected, public.

  2. So that other classes cannot put an object into an invalid state: every change goes through methods that can validate it. It also lets you change how the data is stored later without breaking other code.

  3. A static attribute belongs to the class: there is one copy, shared by all objects, used as ClassName.attribute. A non-static (instance) attribute belongs to each object: every object has its own copy.

    • final variable or attribute: its value can be assigned only once (a constant).
    • final method: it cannot be overridden.
    • final class: it cannot be extended.

Practice exercises

  1. Create a class in one package and try to access its private, default, protected and public members from another class. Record which lines fail to compile.
  2. Add a static counter to a Car class that counts how many cars were created.
  3. Define a constant MAX_SPEED with static final and use it to limit a car's speed.