SyntaxPilot
Courses/Low-Level Design/Lesson 2

Low-Level Design · Lesson 2 of 90 · 14 min

Java for LLD 1: classes, objects and access control

classobjectinstancefieldmethodconstructorconstructor overloadingthisnewreference variablesnullaccess modifiers public private protected package-privatepackagesimports

These are the notes for Low-Level Design (LLD) episode 2. Every design in this course is built from classes, so this episode builds the class from scratch, as the fix for a tiny bank that keeps breaking. You will learn class, object, instance, field, method, constructor, constructor overloading, this, new, reference variables, null, the four access levels (public, private, protected, package-private), packages and imports, static fields and methods, final variables, and the object lifecycle with garbage collection. Every program was run with javac Main.java && java -cp . Main (Java 21), the same way the SyntaxPilot compiler runs it; all outputs and error messages are real.

The problem: a bank in loose variables

Two customers: Aarav has Rs 500, Meera has Rs 800. The obvious way is one variable (a named box holding one value) per detail, and a small method to deposit:

public class Main {
    static void deposit(int balance, int amount) {
        balance = balance + amount;
    }
    public static void main(String[] args) {
        String owner1 = "Aarav"; int balance1 = 500;
        String owner2 = "Meera"; int balance2 = 800;
        deposit(balance1, 200);
        System.out.println(owner1 + ": " + balance1);
        System.out.println(owner2 + ": " + balance2);
    }
}
Aarav: 500
Meera: 800

The deposit vanished. When you pass an int to a method, Java passes a copy of the value. deposit added 200 to its own copy, which was thrown away.

Why this design fails:

  1. The method received a copy, so it could not change the real balance.
  2. owner1 and balance1 belong together, but only their names say so.
  3. 10,000 customers would need 20,000 loose variables.

What we want: one box per customer that holds the data and the actions together.

Class, object, instance, field, method

Real life (a bank's account-opening form) Java Meaning
The blank form design class Account A blueprint: which data and which actions every account has
Aarav's filled-in form object / instance One real account made from the class. "Instance of Account" = "object of class Account"
The boxes on the form (name, balance) fields Variables that live inside each object; every object has its own set
The "deposit" counter service method An action that works on that object's own fields
class Account {
    String owner;
    int balance;
    void deposit(int amount) { balance = balance + amount; }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account();
        a.owner = "Aarav"; a.balance = 500;
        Account m = new Account();
        m.owner = "Meera"; m.balance = 800;
        a.deposit(200);
        System.out.println(a.owner + ": " + a.balance);
        System.out.println(m.owner + ": " + m.balance);
    }
}
Aarav: 700
Meera: 800
  • new Account() creates a brand-new object from the blueprint.
  • The dot (a.owner, a.deposit(200)) means "this object's field / method".
  • deposit changed a's own balance; Meera's object was untouched.

new, reference variables and null

Real life Java
Building a house new Account() creates the object in memory
A slip of paper with the house's address A reference variable like Account a: it holds the object's address, not the object
Photocopying the slip: two slips, one house Account b = a; copies the reference, not the object
A blank slip null: a reference that points to no object
class Account {
    String owner;
    int balance;
    void deposit(int amount) { balance = balance + amount; }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account();
        a.owner = "Aarav"; a.balance = 500;
        Account b = a;
        b.deposit(100);
        System.out.println(a.owner + ": " + a.balance);
        Account c = null;
        c.deposit(50);
    }
}
Aarav: 600
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Account.deposit(int)" because "<local3>" is null
    at Main.main(Main.java:14)
  • b.deposit(100) changed the object that a also refers to, so a.balance is 600.
  • Calling a method on null throws a NullPointerException. <local3> means "local variable number 3" (our c); Java shows that instead of the name because the class was compiled without debug names.
  • Fix: never call a method on a reference that might be null; check it (if (c != null)) or make sure it always gets a real object.

Primitives vs references. int, double, boolean, char (and long, float, short, byte) are primitive types: the variable holds the value itself, and assignment copies the value. Every other type (String, Account, arrays) is a reference type: the variable holds an address. Java always passes a copy of the variable to a method; for a reference that copy is a second slip to the same house, which is why a.deposit(200) works but deposit(balance1, 200) did not.

Constructors

Filling fields line by line is fragile: forget one and the object is half-built. Java fills unset fields with default values: null for references, 0 for numbers, false for booleans. A constructor is special code that runs automatically when you write new, so the object is set up the moment it is made. It has the same name as the class and no return type.

The owner = owner trap

class Account {
    String owner;
    int balance;
    Account(String owner, int balance) {
        owner = owner;
        balance = balance;
    }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Aarav", 500);
        System.out.println(a.owner + ": " + a.balance);
    }
}
null: 0

Inside the constructor, owner means the parameter (the input the constructor receives), which shadows (hides) the field with the same name. owner = owner copies the parameter into itself. The field is never set.

The fix: this

this means the very object being built (or, inside a method, the object the method was called on). this.owner is the field; plain owner is the parameter.

Account(String owner, int balance) {
    this.owner = owner;
    this.balance = balance;
}
Aarav: 500

Constructor overloading

Having several constructors with different parameter lists is constructor overloading. Java picks the one whose parameters match the arguments. this(...) as the first line calls another constructor of the same class, so the real setup lives in one place:

class Account {
    String owner;
    int balance;
    Account(String owner, int balance) {
        this.owner = owner;
        this.balance = balance;
    }
    Account(String owner) {
        this(owner, 0);
    }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Aarav", 500);
        Account k = new Account("Kabir");
        System.out.println(a.owner + ": " + a.balance);
        System.out.println(k.owner + ": " + k.balance);
    }
}
Aarav: 500
Kabir: 0

If you write no constructor at all, Java gives the class an invisible default constructor with no parameters. As soon as you write any constructor, that default one disappears.

Access modifiers: protecting the rules

Without protection, any code anywhere can break the bank's rules:

Account a = new Account("Aarav", 500);
a.balance = -5000;
System.out.println(a.owner + ": " + a.balance);
Aarav: -5000

Mark the field private (only code inside Account can touch it):

private int balance;
Main.java:12: error: balance has private access in Account
        a.balance = -5000;
         ^
Main.java:13: error: balance has private access in Account
        System.out.println(a.owner + ": " + a.balance);
                                             ^
2 errors

Outside code now goes through public methods that enforce the rules, and getters (methods that return a field's value without letting you change it):

class Account {
    private final String owner;
    private int balance;
    Account(String o, int b) { owner = o; balance = b; }
    public void deposit(int amount) {
        if (amount <= 0) { System.out.println("Rejected"); return; }
        balance = balance + amount;
    }
    public int getBalance() { return balance; }
    public String getOwner() { return owner; }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Aarav", 500);
        a.deposit(200);
        a.deposit(-5000);
        System.out.println(a.getOwner() + ": " + a.getBalance());
    }
}
Rejected
Aarav: 700

(When parameter names differ from field names, like o and b, you don't need this. Using the same names with this. is the more common style.)

The four access levels

Modifier Who can use it Real-life picture UML marker
public Every class, everywhere The shop at the front of your house +
protected Same package + subclasses (classes built on top of this one, see episode 8) Your family, including your children's homes #
(no keyword) package-private Only classes in the same package Your housing society ~
private Only this class Your diary -

Design rule of thumb: fields private, and open only the methods others really need. The class then guards its own rules (this idea is called encapsulation, episode 6).

+----------------------------+
|          Account           |
+----------------------------+
| - owner: String {final}    |
| - balance: int             |
+----------------------------+
| + Account(owner, balance)  |
| + deposit(amount): void    |
| + getBalance(): int        |
| + getOwner(): String       |
+----------------------------+

static fields and static methods

Goal: count the bank's customers. A normal field gives every object its own counter:

class Account {
    String owner;
    int count = 0;
    Account(String owner) {
        this.owner = owner;
        count = count + 1;
        System.out.println(owner + " joined. Customers: " + count);
    }
}
public class Main {
    public static void main(String[] args) {
        new Account("Aarav");
        new Account("Meera");
        new Account("Kabir");
    }
}
Aarav joined. Customers: 1
Meera joined. Customers: 1
Kabir joined. Customers: 1

A static field belongs to the class itself: exactly one copy shared by all objects (one board on the bank's wall). Change int count to static int count:

Aarav joined. Customers: 1
Meera joined. Customers: 2
Kabir joined. Customers: 3

A static method also belongs to the class and is called on the class name, with no object: Account.customers(). It has no this, so it cannot use instance fields:

static int showBalance() { return balance; }
Main.java:7: error: non-static variable balance cannot be referenced from a static context
    static int showBalance() { return balance; }
                                      ^
1 error

Use static for things that truly belong to the whole class (a counter, a helper like Math.max). Keep it rare in designs: shared state is hard to test and to make thread-safe.

final variables

A final variable can be assigned exactly once. A final field must be set by the time the constructor finishes, and never again:

class Account {
    final String number;
    String owner;
    Account(String number, String owner) {
        this.number = number;
        this.owner = owner;
    }
}
// in main:
Account a = new Account("SB-1001", "Aarav");
a.owner = "Aarav Shah";      // fine
a.number = "SB-9999";        // not allowed
Main.java:13: error: cannot assign a value to final variable number
        a.number = "SB-9999";
         ^
1 error

Without that line it prints SB-1001 Aarav Shah. Note: final on a reference means the reference can't change; the object it points to can still change unless its own fields are final.

Packages and imports

  • A package is a named group of classes, like a folder (or a supermarket aisle). The first line of bank/Account.java would be package bank;.
  • Every class has a full name: java.util.ArrayList is class ArrayList in package java.util.
  • An import lets you use the short name: import java.util.ArrayList; (or import java.util.*; for the whole package).
  • No import is needed for classes in the same package or in java.lang (String, Math, System).

Without the import:

public class Main {
    public static void main(String[] args) {
        ArrayList<String> owners = new ArrayList<>();
        owners.add("Aarav");
        owners.add("Meera");
        System.out.println(owners);
    }
}
Main.java:3: error: cannot find symbol
        ArrayList<String> owners = new ArrayList<>();
        ^
  symbol:   class ArrayList
  location: class Main
...
2 errors

A symbol is any name in your code. With import java.util.ArrayList; at the top it prints [Aarav, Meera].

The object lifecycle and garbage collection

Stage Hotel picture Java
Created Check-in new Account(...) allocates the object in memory (the heap)
In use A guest holds the key card At least one reference points to it
Unreachable Checked out, no key card left No reference points to it (for example a = null; and no other copy)
Collected Housekeeping cleans the room The garbage collector, part of the JVM, frees its memory automatically, at a time it chooses

You never delete objects by hand in Java; you just stop referring to them. System.gc() only suggests a collection; it is not guaranteed.

Common mistakes

Mistake Exact message / symptom Why Fix
owner = owner; in a constructor No error: prints null: 0 Both names mean the parameter this.owner = owner;
Calling a method on null NullPointerException: Cannot invoke "Account.deposit(int)" because "<local3>" is null A blank slip: no object Give the variable a real object, or check for null
Touching a private field from outside balance has private access in Account private = this class only Call a public method
Instance field in a static method non-static variable balance cannot be referenced from a static context No object (no this) in a static method Make it an instance method
Assigning a final field twice cannot assign a value to final variable number final = set once Set it only in the constructor
Using ArrayList without import cannot find symbol ... class ArrayList Java doesn't know which ArrayList import java.util.ArrayList;
Expecting a method to change an int argument No error: the value is unchanged Methods get a copy of primitives Put the value in an object and call its method

Mini project: a safer account

Add withdraw(amount) that refuses amounts that are zero, negative or more than the balance, a final account number, and a static customer counter.

Solution
class Account {
    private static int count = 0;
    private final String accountNumber;
    private final String owner;
    private int balance;
    Account(String accountNumber, String owner, int balance) {
        this.accountNumber = accountNumber;
        this.owner = owner;
        this.balance = balance;
        count++;
    }
    public boolean withdraw(int amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }
    public int getBalance() { return balance; }
    public static int customers() { return count; }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account("SB-1001", "Aarav", 500);
        new Account("SB-1002", "Meera", 800);
        System.out.println(a.withdraw(200) + " " + a.getBalance());
        System.out.println(a.withdraw(900) + " " + a.getBalance());
        System.out.println("Customers: " + Account.customers());
    }
}
true 300
false 300
Customers: 2

Practice

  1. What does this print, and why?
static void change(String s) { s = "Meera"; }
// main:
String name = "Aarav";
change(name);
System.out.println(name);
Solution

Aarav. The method gets a copy of the reference; s = "Meera" points that copy at a new String, and the caller's name is untouched.

  1. String a = new String("hi"), b = new String("hi"); What do a == b and a.equals(b) print?
Solution

false then true (both run). == on references asks "same object?"; equals asks "same content?". Episode 4 covers equals in depth.

  1. Which access level would you give (a) a bank account's balance field, (b) its deposit method, (c) a helper method used only by other classes in the same package?
Solution

(a) private, (b) public, (c) package-private (no keyword).

  1. Why does adding a constructor Account(String owner) make new Account() stop compiling?
Solution

Java only adds the invisible no-argument default constructor when the class has no constructors. Once you write one, you must write Account() yourself if you still want it.

Quick quiz

Account a = new Account("Aarav", 500);
Account b = a;
b.deposit(100);
a = null;
System.out.println(b.getBalance());
  • 500
  • 600
  • NullPointerException
  • 0
Answer

600. a and b were two references to one object. Setting a to null removes one reference; b still points to the object, which has 600. (A version of this code was run and printed 600.)

Interview questions

  1. Class vs object? A class is the blueprint; an object is one instance created from it with new.
  2. What does this refer to? The current object: the one being constructed, or the one a method was called on.
  3. Why make fields private? So the class can enforce its rules (no negative balance) and change its internals later without breaking callers.
  4. Difference between protected and package-private? Both allow the same package; protected also allows subclasses in other packages.
  5. When is static a bad idea in a design? For state that belongs to individual objects, and for shared mutable state that makes testing and concurrency hard.
  6. Is Java pass-by-value or pass-by-reference? Always pass-by-value. For objects, the value passed is a copy of the reference.
  7. When is an object eligible for garbage collection? When no live reference can reach it.

Glossary

Term Meaning, with an example
Variable A named box holding one value. int balance1 = 500;
Class A blueprint for objects: fields + methods. class Account
Object One thing made from a class. new Account()
Instance Another word for object: "an instance of Account"
Field A variable inside each object. int balance;
Method An action on an object's fields. deposit(int amount)
Parameter The input a method or constructor receives. amount in deposit(int amount)
Argument The actual value passed in. 200 in deposit(200)
Constructor Setup code that runs on new; same name as the class, no return type
Default constructor The no-argument constructor Java adds only if you write none
Constructor overloading Several constructors with different parameters. Account(String) and Account(String, int)
this The current object. this.owner = owner;
this(...) Calling another constructor of the same class
new Creates an object and returns a reference to it
Reference variable A variable that holds an object's address. Account a
Primitive type A type whose variable holds the value itself: int, double, boolean, char...
Reference type Any class, interface or array type; its variables hold addresses
null A reference to no object
NullPointerException The exception thrown when you use null as if it were an object
Default value What Java puts in an unset field: null, 0, false
Shadowing A parameter or local variable hiding a field with the same name
Access modifier A keyword that controls who can use a member: public, protected, private
public Usable from everywhere
private Usable only inside the same class
protected Same package + subclasses
Package-private No keyword: same package only
Subclass A class built on top of another (extends), covered in episode 8
Getter A method that returns a field's value. getBalance()
Package A named group of classes, like a folder. java.util
Import Lets you use a class by its short name. import java.util.ArrayList;
Symbol Any name in code (class, variable, method)
static field One copy shared by the whole class. static int count
static method A method of the class, called without an object. Account.customers()
final variable Can be assigned only once. final String number;
Object lifecycle An object's life: created, used, unreachable, collected
Heap The memory area where objects live
Unreachable No reference can reach the object any more
Garbage collector The part of the JVM that frees memory of unreachable objects automatically

Summary

  • A class is a blueprint; an object (instance) is made with new; fields hold data, methods act on it.
  • Variables of class types hold references; copying one gives two names for one object; null means none.
  • Constructors set objects up; this.field = param avoids the shadowing trap; overload with this(...).
  • Make fields private; expose public methods that enforce rules.
  • static = belongs to the class (one copy); final = assigned once.
  • Packages group classes; import uses short names.
  • Objects nobody refers to are cleaned up by the garbage collector.

Next episode: Java for LLD 2: interfaces, enums, records and generics.