Self-check questions
Write your answers first, then open the answers to check them.
- List the four access levels in Java from most to least restrictive.
- Why should attributes usually be private?
- What is the difference between a static and a non-static attribute?
- What are the three uses of
final?
Show answers
private, default (no keyword, also called package-private),protected,public.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.
A
staticattribute belongs to the class: there is one copy, shared by all objects, used asClassName.attribute. A non-static (instance) attribute belongs to each object: every object has its own copy.finalvariable or attribute: its value can be assigned only once (a constant).finalmethod: it cannot be overridden.finalclass: it cannot be extended.
Practice exercises
- 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.
- Add a static counter to a Car class that counts how many cars were created.
- Define a constant
MAX_SPEEDwithstatic finaland use it to limit a car's speed.