8.4 Constructors, Access Modifiers & Encapsulation Principles

Key Takeaways

  • A constructor must match the exact class name and declare no return type (not even void); it cannot be static, final, or abstract.

  • For an ordinary class with no declared constructors, the compiler supplies a default constructor with the class’s access level. Declaring any constructor suppresses that default.

  • In Java 8, this(...) must be the first constructor statement, cannot create a cycle, and cannot use the instance under construction in its arguments.

  • For a protected instance member in another package, code in a subclass may access it through that subclass type or a subtype. A qualifier of the superclass type fails the access check.

  • Encapsulation controls how callers observe or change state. Copy mutable data on input or output when sharing it would let callers bypass the class’s rules.

Last updated: November 2026

Constructors, Access Modifiers & Encapsulation Principles

Object construction, access control, and encapsulation work together to ensure that every object starts in a valid state and cannot be corrupted by outside callers. Exam questions in this topic focus heavily on constructor traps, this(...) chaining rules, cross-package protected visibility, and mutable-object leaks.

Constructor Rules & Pseudo-Constructor Traps

A constructor participates in initializing a new object. A class instance creation expression selects a constructor, and this(...) or super(...) can delegate within the constructor chain. Ordinary class constructors follow these rules:

  1. Exact name match: The name must match the class name identically (case-sensitive).
  2. No return type: Not even void! Adding a return type turns the declaration into an ordinary method.
  3. No non-access modifiers: Constructors may use public, protected, package-private (no keyword), or private—never static, final, abstract, synchronized, or native. An enum constructor cannot be public or protected.
public class Sensor {
    private int id;

    public Sensor(int id) {       // Valid constructor
        this.id = id;
    }

    public void Sensor() {        // COMPILES, but this is a regular METHOD, NOT a constructor!
        System.out.println("Trap!");
    }
}

If you call new Sensor() on the class above, compilation fails because Sensor(int) exists (suppressing the default constructor) and void Sensor() is just a method!

The Compiler-Inserted Default Constructor

For an ordinary top-level class that declares no constructors, the compiler supplies a default no-argument constructor with the same access as the class. It acts like ClassName() { super(); } and can fail to compile if the superclass has no accessible no-argument constructor without a throws clause. A class may instead explicitly declare its own no-argument constructor. That is a user-defined constructor.

The moment you write any constructor (even a private or parameterized one), the compiler does not generate a default no-arg constructor:

class Ticket {
    String seat;
    Ticket(String seat) { this.seat = seat; }
}

// Ticket t = new Ticket(); // COMPILE ERROR: constructor Ticket in class Ticket cannot be applied to given types
Ticket t = new Ticket("12A"); // Compiles cleanly

Constructor Overloading & this(...) Chaining

A class can overload multiple constructors with different parameter lists and delegate common setup using this(...):

public class ServerConfig {
    private final String host;
    private final int port;
    private static final int DEFAULT_PORT = 8080;

    public ServerConfig() {
        this("localhost", DEFAULT_PORT); // Must be statement #1!
    }

    public ServerConfig(String host) {
        this(host, DEFAULT_PORT);
    }

    public ServerConfig(String host, int port) {
        this.host = host;
        this.port = port;
    }
}

Four hard compiler rules govern this(...):

  • First statement only: this(...) must be the very first statement in the constructor body (System.out.println(); this(1); fails compilation). Consequently, a constructor cannot contain both this(...) and super(...).
  • No reference to the current instance in arguments: this(this.defaultPort) fails because it uses the object under construction. Arguments can use parameters, static fields, or another object’s accessible members.
  • No recursive cycles: Two constructors calling each other (A() { this(1); } and A(int x) { this(); }) fail compilation with recursive constructor invocation.
  • Calling a constructor without new: Inside a method, ServerConfig("a", 80); is parsed as a method call. To construct a new ServerConfig using ordinary Java syntax, write new ServerConfig("a", 80).

Java's Four Access Modifiers

Java has four access levels for ordinary class members. Package access uses no modifier. This table assumes the declaring type is accessible and the callers in other classes are separate top-level classes. Nested declarations under the same top-level type can access its private members.

ModifierSame ClassSame Package (Non-Subclass)Different Package (Subclass)Different Package (Non-Subclass)
publicYesYesYesYes
protectedYesYesYes (with a qualifying-type restriction for instance members)No
(package-private)YesYesNoNo
privateYesNoNoNo

Top-level classes and interfaces can only be public or package-private; marking a top-level class protected or private fails compilation.

The Cross-Package protected Inheritance Trap

The most tested cell in the visibility matrix is Different Package (Subclass) for protected members. Look carefully at how the reference type controls compilation:

// File: alpha/Parent.java
package alpha;
public class Parent {
    protected int code = 42;
}

// File: beta/Child.java
package beta;
import alpha.Parent;

public class Child extends Parent {
    public void inspect(Child c, Parent p) {
        System.out.println(code);   // Legal: inherited via 'this' (Child)
        System.out.println(c.code); // Legal: accessed through Child reference
        // System.out.println(p.code); // COMPILE ERROR: code has protected access in Parent!
    }
}

Why does p.code fail inside Child? Because Child lives in package beta, not alpha. Outside package alpha, the access to this protected instance field is allowed from the subclass body with a Child or narrower qualifier. In this context p.code fails because the qualifier has compile-time type Parent. Protected static members and protected constructors have separate qualification rules.

Encapsulation Principles & Defensive Copying

Encapsulation protects an object's internal invariants by hiding data behind controlled methods. Start with private fields and expose only operations the caller needs. A class can provide a getter without a setter. If it accepts a mutable input whose contents it needs to own, copy that input before storing it. If it exposes mutable state, return a copy or another representation that does not let the caller mutate the internal state.

import java.util.Arrays;

public class ExamProfile {
    private String candidate;
    private boolean active;
    private int[] scores;

    public ExamProfile(String candidate, boolean active, int[] scores) {
        setCandidate(candidate);   // Apply the same validation used for later updates
        this.active = active;
        // Defensive copy: caller mutating original array cannot corrupt this.scores
        this.scores = (scores == null) ? new int[0] : Arrays.copyOf(scores, scores.length);
    }

    public String getCandidate() { return candidate; }
    public boolean isActive()    { return active; }

    public int[] getScores() {
        // Defensive copy: caller mutating returned array cannot corrupt this.scores
        return Arrays.copyOf(scores, scores.length);
    }

    public final void setCandidate(String candidate) {
        if (candidate == null || candidate.trim().isEmpty()) {
            throw new IllegalArgumentException("Candidate name required");
        }
        this.candidate = candidate;
    }
}

Tip

Immutable types such as String, Integer, and java.time.LocalDate do not require defensive copying because callers cannot modify their contents. Copy when a mutable alias would expose internal state. A shallow copy of an object array or list still shares its element objects, so consider whether those objects also need isolation.

Test Your Knowledge

Which class definition fails to compile?

A
class A {
    private A() {}
    public A(int x) { this(); }
}
B
class B {
    public void B() {}
}
C
class C {
    static int def = 5;
    C() { this(def); }
    C(int x) {}
}
D
class D {
    int def = 5;
    D() { this(def); }
    D(int x) {}
}
Test Your Knowledge

Given package p1; public class Base { protected int val = 9; } and package p2; import p1.Base; public class Sub extends Base { ... }, which statement inside a method of Sub fails to compile?

A

int a = val;

B

Base b = new Sub(); int x = b.val;

C

Sub s = new Sub(); int y = s.val;

D

int z = this.val;

Test Your Knowledge

A class Ledger has a private int[] entries; field initialized from a caller-supplied array and exposed via public int[] getEntries(). What change prevents external callers from modifying Ledger's internal array contents?

A

Declare private final int[] entries; and return entries directly from getEntries()

B

Change entries to protected and validate indices in setEntries(int[])

C

Copy the incoming array in the constructor/setter and return Arrays.copyOf(entries, entries.length) from getEntries()

D

Add static to getEntries() so callers cannot use an instance reference

Sections you finish are checked off in the contents.