Home
6Access Control, static, final & Nested Classes
6

Topic 6 of 13 · Lectures 8–9

Access Control, static, final & Nested Classes

Who may use a field or method (private, default, protected, public), members that belong to the class rather than an object (static), constants and fixed references (final), and classes inside classes.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

How does every Student object know how many students have been created so far — without any of them being in charge?

A static field belongs to the class itself, so there is exactly one copy shared by every object. Combined with access modifiers and final, it lets you control precisely who sees what, and what may never change.

We finish with nested classes: classes defined inside other classes to keep helper code close to where it is used.

Outline · Lectures 8–9

Topics in this chapter

Select a topic to jump to the slide that explains it.

  1. Access modifiers
  2. static fields and methods
  3. final variables and constants
  4. Nested and inner classes

Concept 1 of 4

Access modifiers

ModifierSame classSame packageSubclass (other package)Everywhere
private✓✗✗✗
(none) default / package-private✓✓✗✗
protected✓✓✓ (through inheritance)✗
public✓✓✓✓
  • Top-level classes can only be public or default.
  • Good default: fields private, methods public only if other classes need them, helpers private.
  • Access is checked per class, not per object: a Student method may read another Student’s private fields.

Interactive

Access-modifier checker

Concept 2 of 4

static fields and methods

One static count lives with the class; each object has its own id.

static fields and methods

class Counter {
    static int count = 0;   // one per class
    int id;                 // one per object
    Counter() {
        count++;
        id = count;
    }
    static int getCount() { return count; }
}
Counter.getCount();         // call via the class
  • A static member belongs to the class; use it through the class name: Math.sqrt, Integer.parseInt.
  • A static method has no this, so it cannot use instance fields or instance methods directly.

Step through the code

Trace: a shared static counter

The static area holds one count. Every constructor call increases it and copies the current value into that object’s own id.

Step through the code

Trace: a shared static counter (cont.)

Interactive

Static or not? Predict the compiler

Code example

Static blocks and utility classes

class MathUtil { static final double[] SQUARES = new double[5]; static { // runs once, when the class loads for (int i = 0; i < SQUARES.length; i++) SQUARES[i] = i * i; System.out.println("MathUtil loaded"); } private MathUtil() {} // no objects needed static int max(int... v) { int m = v[0]; for (int x : v) if (x > m) m = x; return m; } } System.out.println("start"); System.out.println(MathUtil.max(4, 9, 2)); System.out.println(MathUtil.SQUARES[3]);
Output
start
MathUtil loaded
9
9.0
  • A static block initialises static data once, the first time the class is used.
  • A utility class has only static members and a private constructor (like Math and Arrays).

Step through the code

Trace: when does a static block run?

Not at program start: the class is loaded, and its static block runs, on the first use of MathUtil.

Step through the code

Trace: when does a static block run? (cont.)

Concept 3 of 4

The final keyword

Applied toMeaningExample
Local variable / parameterCan be assigned only once.final int max = 100;
FieldMust be set once — at declaration or in every constructor (“blank final”).private final int id;
static final fieldA class constant; name it in UPPER_CASE.static final double PI = 3.14159;
Reference variableThe arrow cannot move, but the object can still change.final int[] a = {1}; a[0] = 5; // OK
MethodCannot be overridden by a subclass.final void pay()
ClassCannot be extended.final class String

Concept 4 of 4

Nested classes

Four kinds of class that can live inside another class.

Concept 4 of 4

Nested classes (cont.)

KindKey facts
static nestedLike a normal class placed inside for grouping; no link to an outer object. new Outer.Nested()
inner (non-static)Every inner object belongs to an outer object and can use its private fields. outer.new Inner()
localDeclared inside a method; can use effectively-final local variables.
anonymousA one-off class without a name, written where it is used — often to implement an interface.

Code example

Inner and anonymous classes in code

class Bank { private String name = "GUB Bank"; private int opened = 0; class Account { // inner class int no = ++opened; // uses outer's field String info() { return name + " #" + no; } } static class Rate { // static nested static double of(int years) { return years > 5 ? 0.08 : 0.06; } } } Bank b = new Bank(); Bank.Account a1 = b.new Account(); Bank.Account a2 = b.new Account(); System.out.println(a1.info() + ", " + a2.info()); System.out.println(Bank.Rate.of(7)); Runnable r = new Runnable() { // anonymous class public void run() { System.out.println("running"); } }; r.run(); Runnable r2 = () -> System.out.println("lambda"); // same idea, Java 8+ r2.run();
Output
GUB Bank #1, GUB Bank #2
0.08
running
lambda

Worked example 1 of 3

Worked example 1

Why does this not compile?
class A { int x; static void show() { System.out.println(x); } }
Show the solution
show() is static, so it runs without any object — there is no this.x to print. Make show() an instance method, or make x static, or pass an A object as a parameter.

Worked example 2 of 3

Worked example 2

Class Pay in package hr declares protected double rate;. Which classes can use rate?
Show the solution
  • Pay itself.
  • Every class in package hr.
  • Subclasses of Pay in other packages — through inheritance (their own objects).
  • No other classes.

Worked example 3 of 3

Worked example 3

Give each Order a unique, unchangeable number 1001, 1002, …
Show the solution
class Order {
    private static int next = 1001;
    private final int no;
    Order() { no = next++; }
    int getNo() { return no; }
}
A static counter shared by all orders, and a final instance field set once in the constructor.

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. What is the difference between default (package-private) and protected access?
Show the answer
Both allow access within the same package; protected additionally allows subclasses in other packages.
2. Can a static method call an instance method directly? Explain.
Show the answer
No — an instance method needs an object (this), and a static method has none. It must create or receive an object first: obj.method().
3. Is this legal? final StringBuilder sb = new StringBuilder(); sb.append("x");
Show the answer
Yes. final fixes the reference, not the object. sb = new StringBuilder(); would be illegal.

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. Write a class Circle that counts how many circles exist and exposes the count with a static getter.
Show the answer
class Circle {
    private static int count;
    private double r;
    Circle(double r) { this.r = r; count++; }
    static int getCount() { return count; }
}
5. How do you create an object of an inner class Inner defined in Outer?
Show the answer
Outer o = new Outer(); Outer.Inner in = o.new Inner(); — an inner object always needs an outer object.
6. Why is Math’s constructor private?
Show the answer
All its members are static, so objects are pointless; a private constructor prevents new Math().

Check yourself

Quiz

Summary

Summary

  • private → class only; default → package; protected → package + subclasses; public → everyone.
  • static members belong to the class (one copy); static methods have no this.
  • final: variables assigned once, methods not overridable, classes not extendable. static final = constant.
  • Nested classes: static nested, inner (tied to an outer object), local and anonymous.