Java Access Specifiers (public, private, protected) & static/final

⚑ Direct Answer & Key Takeaway

Java access specifiers control member visibility across classes and packages: `private` restricts access strictly inside the declaring class, package-private (default, no keyword) opens access within the same package, `protected` extends access to subclasses across packages, and `public` permits universal access. Non-access modifiers change lifecycle and mutability: `static` creates one class-level member shared across all objects, whereas `final` locks variable reassignment, prevents method overriding, and blocks class inheritance.

πŸ“₯ Want Solved Board PDF & Practice Sheet? Get Sent Free on WhatsApp β†’

1. Visibility Matrix: private, default, protected, and public

CISCE Section A expects you to recall exact visibility boundaries across four scopes: same class, same package non-subclass, different package subclass, and different package non-subclass. A `private` field achieves data hiding and encapsulation because external classes can only read or update it via `public` getters and setters. Omitting any keyword creates package-private (friendly) visibility, allowing classes inside the same BlueJ package folder to read the member directly while blocking outside packages. Marking a member `protected` grants same-package visibility plus inheritance access to subclasses living in external packages. Finally, `public` allows unrestricted access everywhere.

  • private: visible only inside the same class (used for instance variables like balance).
  • default (no keyword): visible inside the same class and same package only.
  • protected: visible in same package plus subclasses in any package.
  • public: visible across all classes and packages; required for main().

2. How static Shares Memory Across Objects

Unlike instance variables, which receive fresh memory inside every object created with `new`, a `static` variable (class variable) is allocated once when the JVM loads the class. If `count` is declared `static int count = 0;`, incrementing `count` inside one object immediately changes what every other object reads. Similarly, `static` methods such as `Math.sqrt()` or `main()` belong to the class itself and can run without instantiating an object. However, a `static` method cannot directly access non-static instance variables or `this`, because no specific object exists during a static call.

  • Access static members cleanly via ClassName.memberName rather than object references.
  • A static method calling a non-static field directly triggers 'non-static variable cannot be referenced from a static context'.
  • Static counters are a classic ICSE Section A trace question across multiple new calls.

3. Using final for Constants, Methods, and Classes

The `final` keyword enforces immutability at three distinct levels tested in board MCQs. Applied to a variable such as `final double PI = 3.14159;`, it locks the value permanently after initialization; any later reassignment fails compilation. By Java convention, `static final` constants use uppercase names with underscores. Applied to a method, `final` prevents any child class from overriding its behavior while still allowing inheritance. Applied to an entire classβ€”just like Java's built-in `String` and `Math` classesβ€”`final` forbids subclassing completely via `extends`. Do not confuse `final` with `finally` (exception handling).

  • final variable: value cannot change after first assignment.
  • final method: cannot be overridden by a subclass.
  • final class: cannot be inherited/extended by any subclass.

4. Encapsulation, static Counter & final Constant Demo

import java.util.*;

public class BankAccountScope {
    public static final double MIN_BALANCE = 1000.0;
    private static int totalAccounts = 0;

    private String holderName;
    private double balance;
    protected String branchCode;

    public BankAccountScope(String holderName, double balance, String branchCode) {
        this.holderName = holderName;
        this.balance = (balance >= MIN_BALANCE) ? balance : MIN_BALANCE;
        this.branchCode = branchCode;
        totalAccounts++;
    }

    public double getBalance() {
        return balance;
    }

    public static int getTotalAccounts() {
        return totalAccounts;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name and opening balance: ");
        String name = sc.next();       // Sample input: Aarav
        double amt = sc.nextDouble();  // Sample input: 2500

        BankAccountScope a1 = new BankAccountScope(name, amt, "ICSE-01");
        BankAccountScope a2 = new BankAccountScope("Meera", 500.0, "ICSE-01");

        System.out.println("Holder 1 Balance: " + a1.getBalance());
        System.out.println("Holder 2 Balance (min enforced): " + a2.getBalance());
        System.out.println("Branch (protected): " + a1.branchCode);
        System.out.println("Total Accounts (static): " + BankAccountScope.getTotalAccounts());
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter name and opening balance: Aarav 2500
Holder 1 Balance: 2500.0
Holder 2 Balance (min enforced): 1000.0
Branch (protected): ICSE-01
Total Accounts (static): 2

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
MIN_BALANCEdoublepublic static final constant enforcing floor (1000.0)
totalAccountsintprivate static class counter shared by all objects (0 -> 2)
holderNameStringprivate encapsulated account holder name ("Aarav" / "Meera")
balancedoubleprivate instance balance read via getBalance() (2500.0 / 1000.0)
branchCodeStringprotected member visible in same package & subclasses ("ICSE-01")
name, amtString, doubleScanner inputs initializing first BankAccountScope object (Aarav, 2500)
🎯 Free Chapter Notes PDF + 1-on-1 Doubt Session

Turn OOP Visibility & Static Rules Into Easy Section A Marks

Get personalized 1-on-1 coaching on Java encapsulation, packages, and BlueJ object memory diagrams tailored to CISCE Class 9 & 10.

πŸ’¬ WhatsApp Now
πŸ”’ 100% Free Study PDF + optional 60-min 1-on-1 doubt check β€’ Zero spam
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing class fields without private and assuming default means private instead of package-private.
  • Avoid Mistake: Trying to print an instance variable directly inside main() without creating an object first.
  • Avoid Mistake: Attempting to reassign a final variable inside an if branch after already initializing it.
  • Examiner / Mentor Tip: Write 'no keyword (package-private / friendly)' cleanly if asked what the default access specifier in Java is.
  • Examiner / Mentor Tip: Cite encapsulation and data hiding whenever asked why instance variables should be declared private.
  • Examiner / Mentor Tip: In static trace questions, keep one single shared memory box for static fields instead of copying per object.

7. Interactive Concept Check Quiz

Question: Which access specifier allows a superclass member to be inherited by a subclass located in a DIFFERENT package, while hiding it from unrelated classes in that other package?

8. Frequently Asked Questions

What is the difference between private and default (package-private) access in Java?
A private member is accessible strictly inside the curly braces of its own class and cannot be read even by classes in the same folder. When you omit an access keyword altogether, Java applies default or package-private access, permitting any class inside the exact same package to access that member directly.
Why must Java's main() method always be declared public and static?
The Java Virtual Machine launches execution from outside your class before any object exists in memory. Declaring main() public lets the JVM invoke it across packages, while declaring it static lets the JVM call ClassName.main() directly without instantiating an object first. Removing either modifier stops the program from running.
Can a top-level Java class in BlueJ be declared private or protected?
No, top-level outer classes in Java may only use public or default (package-private) visibility, because private or protected outer classes would serve no accessible purpose to the JVM or other classes. However, nested inner classes declared inside another class can legally carry private or protected access specifiers.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class