Access Controls, Object creation

new builds the object in 3 steps, and the 4 access levels (private, default, protected, public) decide who may touch what: BookBridge's copies field finally gets a lock.

10 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Anyone can vandalise the catalog

Last lesson ended on an uncomfortable note. Anywhere in the program, any code can write:

b1.copies = -50;

Minus 50 copies. Or a prank: member.fineDue = 0; just before collection. The compiler approves all of it, because every field is currently open to everyone.

Real systems put the records behind a counter: you request a change, and the desk applies the rules. Java's counter is built from access controls.

Theory

What new actually does

First, the precise anatomy of object creation, an exam favourite:

Book b = new Book();

3 things happen:

  • Book b declares a reference variable (it can point at a Book, currently at nothing)
  • new Book() allocates memory for one Book's fields on the heap and runs its constructor
  • = makes the reference point at that new object

Split form is equally legal: Book b; b = new Book();

At a glance

The 4 access levels, narrowest first

ModifierWho can access it
privateOnly code inside the same class
(no modifier / default)Any class in the same package
protectedSame package, plus subclasses anywhere
publicEverywhere

Practical

copies goes behind the counter

class Book {
    private int copies = 3;    // locked: only Book's own code may touch
    String title;              // default access: whole package

    public boolean issue() {   // the public front desk
        if (copies > 0) {
            copies--;
            return true;
        }
        return false;          // never goes below 0
    }

    public int getCopies() { return copies; }
}

public class BookBridge {
    public static void main(String[] args) {
        Book b = new Book();
        b.issue();
        System.out.println(b.getCopies());  // 2
        // b.copies = -50;   // uncomment: compile error, private access
    }
}

Quiz

A field is declared with no access modifier at all: int copies; Who can access it?

  1. Everyone, everywhere: no modifier means no restriction
  2. Only the class that declared it
  3. Any class in the same package
  4. Only subclasses of the declaring class
Show the answer

Any class in the same package

No modifier is itself a level, called default or package-private: the whole package (Java's folder-like grouping, Unit 4) can access it, outsiders cannot. Option A is the trap; Java has no fully-unrestricted-by-omission rule. Option B describes private, option D is roughly protected's extra grant. Exams love default precisely because students assume absence means either everything or nothing.

Think first

When does the vandal get caught?

With copies now private, someone writes b.copies = -50; in BookBridge's main. Before tapping: does this fail when the program runs, or earlier?

Show the answer

Earlier: it never compiles. javac stops with copies has private access in Book. Access control is enforced at compile time, so illegal touches are caught before the program can exist, one more example of Java's robustness. Contrast this with the NullPointerException from last lesson, which is a runtime crash: exams like asking which failures are compile-time and which are runtime.

Watch out

Two subtle rules that cost marks

private is per-class, not per-object: inside Book's own code, one Book may touch another Book's private fields (this.copies + other.copies is legal in a Book method). The wall stands around the class.

Java's protected is wider than C++'s: it grants the whole package PLUS subclasses anywhere. BCA304 taught protected as "class + children only"; carrying that definition into a Java answer loses the package half.

Theory

This is encapsulation being born

Private data plus public methods that guard it: that pattern has a name, encapsulation, one of OOP's 3 pillars, and it gets its full lesson shortly. Notice what the guard bought us: issue() cannot push copies below 0, so the invalid state is now impossible, not just unlikely. Next lesson fixes the other half of the problem: making sure every Book is born with sensible values in the first place, via constructors.

Summary

Key takeaways

  • Book b = new Book(); declares a reference, allocates the object, and connects the 2.
  • 4 access levels: private (class), default (package), protected (package + subclasses), public (everywhere).
  • No modifier means package-private, not open-to-all.
  • Access violations are compile-time errors; the illegal program never runs.
  • private guards the class, not each object: same-class code sees all.
  • Java's protected includes the package, wider than C++'s protected.
  • Memory hook: private, package, protected, public: the door opens wider each step.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Classes and Objects

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Access Controls, Object creation · Java Programming Language · Gri-Learn