Essay
Learning Java, Part 6: A Closer Look at Methods and Classes
Study notes on access modifiers and encapsulation, how Java passes arguments, returning objects, overloading methods and constructors, recursion, static members and static blocks, nested and inner classes, and varargs. Written entirely by an AI model.
Part 4 made classes that anyone could reach into and break. This part adds the controls that let a class protect itself, plus the method features that CITS2005 exams test most: pass-by-value, overloading and static.
Access control and encapsulation
Each field, method and constructor can carry an access modifier:
| Modifier | Visible from |
|---|---|
private |
the same class only |
| (none) | the same package (“package-private”) |
protected |
the same package, plus subclasses anywhere (Part 7) |
public |
everywhere |
The usual design is private fields, public methods. The methods check every change, so the object can never be put into an invalid state:
class Account {
private final String owner;
private long cents;
Account(String owner) {
this.owner = owner;
}
public void deposit(long amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
cents += amount;
}
public boolean withdraw(long amount) {
if (amount <= 0 || amount > cents) return false;
cents -= amount;
return true;
}
public long getCents() { return cents; } // a getter, no setter
public String getOwner() { return owner; }
}
public class AccountDemo {
public static void main(String[] args) {
Account a = new Account("Mei");
a.deposit(5000);
System.out.println(a.withdraw(8000));
System.out.println(a.withdraw(2000));
System.out.println(a.getOwner() + " has " + a.getCents());
// a.cents = -1; // compile error: cents has private access
}
}
false
true
Mei has 3000
Python only has the naming convention _cents; Java’s compiler enforces private. Store money as whole cents in a long rather than a double, for the rounding reasons in Part 2.
How arguments are passed
Java always passes a copy of the value (“pass by value”). The catch is what the value is:
- For a primitive, the copy is the number itself. The method cannot change the caller’s variable.
- For an object, the copy is the reference. The method can change the object it points at, but reassigning its parameter does not affect the caller.
class Box {
int items;
}
public class PassByValue {
static void addOne(int n) { n++; }
static void addItem(Box b) { b.items++; }
static void replace(Box b) { b = new Box(); b.items = 100; }
public static void main(String[] args) {
int n = 5;
addOne(n);
Box box = new Box();
addItem(box);
replace(box);
System.out.println(n + " " + box.items);
}
}
5 1
That is the same behaviour as Python. Exams often ask you to predict this output, so be able to explain each line.
Returning objects
A method can create and return an object. The object survives after the method ends because the caller now holds a reference to it.
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
Point shifted(int dx, int dy) { return new Point(x + dx, y + dy); }
public String toString() { return "(" + x + ", " + y + ")"; }
}
public class Shift {
public static void main(String[] args) {
Point p = new Point(1, 2);
Point q = p.shifted(3, 0);
System.out.println(p + " " + q);
}
}
(1, 2) (4, 2)
Defining toString() controls what println and + show for an object. Part 7 explains why that works.
Overloading
Several methods in one class may share a name if their parameter lists differ in number, type or order. The compiler picks the closest match from the argument types:
public class Overload {
static String show(int x) { return "int " + x; }
static String show(double x) { return "double " + x; }
static String show(String s, int times) { return s.repeat(times); }
public static void main(String[] args) {
System.out.println(show(3));
System.out.println(show(3.0));
System.out.println(show('A')); // char widens to int
System.out.println(show("ab", 3));
}
}
int 3
double 3.0
int 65
ababab
The return type alone does not count: int f() and double f() cannot both exist. Python has no overloading; it uses default arguments instead.
Overloaded constructors and this(…)
Constructors overload the same way. One can call another with this(...), which must be its first statement:
class Order {
private final String tea;
private final int cups;
Order(String tea, int cups) {
this.tea = tea;
this.cups = cups;
}
Order(String tea) { this(tea, 1); } // default of one cup
Order(Order other) { this(other.tea, other.cups); } // copy constructor
public String toString() { return cups + " x " + tea; }
}
public class OrderDemo {
public static void main(String[] args) {
System.out.println(new Order("chai", 3));
System.out.println(new Order("sencha"));
System.out.println(new Order(new Order("puer", 2)));
}
}
3 x chai
1 x sencha
2 x puer
Recursion
A method may call itself. The rules from the Python recursion notes apply unchanged: a base case, and a smaller problem each call. Deep recursion throws StackOverflowError.
public class Factorial {
static long fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
System.out.println(fact(5) + " " + fact(20));
}
}
120 2432902008176640000
fact(21) overflows a long and silently gives a wrong answer, which is a good reason to know the ranges in Part 2. The book’s quicksort exercise is a longer recursive example.
static
A static member belongs to the class, not to any object. There is one copy, shared by all instances, and it can be used without creating an object.
class Ticket {
private static int issued = 0; // shared counter
private final int number;
Ticket() {
issued++;
number = issued;
}
int number() { return number; }
static int issued() { return issued; }
}
public class TicketDemo {
public static void main(String[] args) {
Ticket a = new Ticket();
Ticket b = new Ticket();
System.out.println(a.number() + " " + b.number() + " " + Ticket.issued());
}
}
1 2 2
- Call static members through the class name:
Ticket.issued(),Math.sqrt(2). - A static method has no
this. It cannot use instance fields or call instance methods directly. This is why calling a non-static helper frommaingives the error “non-static method cannot be referenced from a static context”. - A static block,
static { ... }, runs once when the class is first loaded. Use it to set up complex static data. static finalfields are constants:static final int MAX_CUPS = 12;.
Nested and inner classes
A class can be declared inside another:
- A static nested class is an ordinary class that lives inside another for organisation. It cannot see the outer object’s fields.
- An inner class (non-static) is tied to an instance of the outer class and can use its fields, even private ones.
- A local class is declared inside a method; an anonymous class is declared and instantiated in one expression (Part 14 replaces most of these with lambdas).
public class Shop {
private int stock = 3;
class Till { // inner: sees stock
boolean sell() {
if (stock == 0) return false;
stock--;
return true;
}
}
static class Receipt { // static nested: no outer object
static String line(String item) { return "1 x " + item; }
}
public static void main(String[] args) {
Shop shop = new Shop();
Shop.Till till = shop.new Till();
till.sell();
till.sell();
System.out.println(shop.stock + " " + Receipt.line("scone"));
}
}
1 1 x scone
Varargs
A parameter written Type... name accepts any number of arguments, which arrive as an array. It must be the last parameter.
public class Varargs {
static int total(String label, int... values) {
int sum = 0;
for (int v : values) sum += v;
System.out.println(label + ": " + values.length + " values");
return sum;
}
public static void main(String[] args) {
System.out.println(total("none"));
System.out.println(total("three", 4, 5, 6));
}
}
none: 0 values
0
three: 3 values
15
Overloading a varargs method can be ambiguous: with f(int... a) and f(boolean... b), the call f() matches both and does not compile.
Exam-style checks
- “Java passes objects by reference.” Explain why this statement is wrong, using a method that reassigns its parameter.
- Why are fields usually
private? Give an invariant a setter could protect. - Why can’t
maincall an instance method directly? - Can two methods differ only in return type? Why not?
- What is the difference between a static nested class and an inner class?
Where to practise
Schildt’s Chapter 6 improves the queue from Part 5 by making its array private, then overloads its constructors. Do that, then add a static counter of queues created. Write power(base, exp) recursively and iteratively, and an overloaded max for two and three ints plus a varargs version.