Classes, objects and constructors
A class is a blueprint: it declares fields (state) and methods (behaviour). An object is one instance built from that blueprint with new, living on the heap. A variable of a class type holds a reference to the object, not the object itself.
public class Account {private final String owner; // set once, in the constructorprivate long balance; // statepublic Account(String owner) { // constructor: same name, no return typethis(owner, 0); // delegate to the other constructor}public Account(String owner, long opening) {this.owner = owner;this.balance = opening;}public void deposit(long amount) {if (amount <= 0) throw new IllegalArgumentException("amount must be positive");balance += amount;}}Account a = new Account("Ada"); // a holds a reference to a heap object
- If you write no constructor, the compiler adds a no-argument default constructor. Write any constructor and it no longer does.
this(...)calls another constructor of the same class;super(...)calls the parent's. Either must be the first statement.- Fields get default values (0, false, null); local variables don't and must be assigned before use.
The four pillars
| Pillar | What it means | Java tools |
|---|---|---|
| Encapsulation | Hide internal state; expose behaviour through methods that keep it valid. | private fields, getters/setters, validation in methods |
| Abstraction | Show what something does, hide how it does it. | interface, abstract class |
| Inheritance | A class reuses and specialises another (an is-a relationship). | extends, implements |
| Polymorphism | One call, different behaviour depending on the actual object. | Overriding (runtime), overloading (compile time) |
Favour composition over inheritance: give a class a field of another type (has-a) instead of extending it, unless it truly is a specialised version. Deep inheritance trees are hard to change.
Overloading vs overriding
Overloading is several methods with the same name but different parameter lists in one class; the compiler picks one from the argument types (compile-time, static binding). Overriding is a subclass replacing an inherited method with the same signature; the JVM picks the version from the object's real class at run time (dynamic dispatch).
class Shape {double area() { return 0; }}class Circle extends Shape {final double r;Circle(double r) { this.r = r; }@Override double area() { return Math.PI * r * r; } // overriding}class Printer {void print(int x) { System.out.println("int " + x); } // overloadingvoid print(String s) { System.out.println("String " + s); }}Shape s = new Circle(2);s.area(); // Circle.area(): the object's runtime class decides
- Overriding rules: same name and parameters, return type the same or a subtype (covariant), access not more restrictive, may not throw broader checked exceptions.
static,privateandfinalmethods are not overridden. A static method with the same signature in a subclass hides the parent's instead.- Always add
@Override: the compiler then catches typos that would silently create an overload.
Abstract classes vs interfaces
| Abstract class | Interface | |
|---|---|---|
| Inheritance | A class extends only one | A class implements many |
| State | Instance fields allowed | Only public static final constants |
| Constructors | Yes | No |
| Methods | Abstract and concrete, any access | Abstract, default, static, private (Java 9+) |
| Use when | Related classes share code and state | Unrelated classes share a capability (e.g. Comparable) |
interface Payable {long amountDue();default boolean isFree() { return amountDue() == 0; } // Java 8 default method}abstract class Employee implements Payable {protected final String name;Employee(String name) { this.name = name; }abstract long monthlyPay();public long amountDue() { return monthlyPay(); }}
static, final and access modifiers
staticmembers belong to the class, not to any object: one copy shared by all instances. Static methods can't usethis.finalvariable: assigned once.finalmethod: can't be overridden.finalclass: can't be extended (e.g.String).- A
finalreference can't point elsewhere, but the object it points to can still change unless it's immutable.
| Modifier | Same class | Same package | Subclass (other package) | Everyone |
|---|---|---|---|---|
private | ✓ | |||
| (default) | ✓ | ✓ | ||
protected | ✓ | ✓ | ✓ | |
public | ✓ | ✓ | ✓ | ✓ |
equals() and hashCode()
== compares references (same object?). equals() compares meaning (same value?). The contract: if a.equals(b) then a.hashCode() == b.hashCode(). Break it and hash-based collections lose your objects.
public final class Point {private final int x, y;public Point(int x, int y) { this.x = x; this.y = y; }@Override public boolean equals(Object o) {if (this == o) return true;if (!(o instanceof Point p)) return false; // pattern matching, Java 16+return x == p.x && y == p.y;}@Override public int hashCode() { return Objects.hash(x, y); }}// Or simply: public record Point(int x, int y) {} (Java 16+) generates both.
Override equals without hashCode and a HashSet can hold two "equal" points, because they land in different buckets.
See it animated
Interview questions
Try answering out loud first, then open the model answer.
Q1What are the four pillars of OOP? Give a Java example of each.beginner
- Encapsulation:
privatefields with methods likedeposit()that keep the balance valid. - Abstraction: a
Listinterface; callers don't care whether it's anArrayListorLinkedList. - Inheritance:
class Circle extends Shape. - Polymorphism:
Shape s = new Circle(2); s.area();runsCircle'sarea().
Q2What is the difference between overloading and overriding?beginner
Overloading: same method name, different parameters, chosen at compile time. Overriding: a subclass redefines an inherited method with the same signature, chosen at run time from the object's actual class. Overriding needs inheritance; overloading doesn't.
Q3Can you override a static or private method?intermediate
No. Private methods aren't visible to subclasses, so a method with the same name is a brand-new method. A static method with the same signature in a subclass hides the parent's: which one runs depends on the reference's declared type, not the object, so there is no polymorphism.
Q4Abstract class or interface: how do you choose?intermediate
Use an interface to describe a capability that unrelated classes can share (a class can implement many). Use an abstract class when closely related classes share state or code and you want constructors or non-public members. Since Java 8 interfaces can have default methods, so shared behaviour alone is no longer a reason to pick an abstract class.
Q5Why must you override hashCode() when you override equals()?intermediate
Hash-based collections first use hashCode() to find a bucket, then equals() inside it. Two equal objects with different hash codes end up in different buckets, so contains() fails and a Set can hold duplicates. The contract: equal objects must have equal hash codes (unequal objects may share one).
Q6Is Java pass-by-value or pass-by-reference?intermediate
Always pass-by-value. For objects, the value copied is the reference. So a method can change the object's fields through the copy, but reassigning the parameter doesn't affect the caller's variable.
void reset(Account a) { a = new Account("x"); } // caller's variable unchangedvoid empty(Account a) { a.withdrawAll(); } // caller sees the change
Q7What does final mean on a variable, a method and a class?beginner
- Variable: can be assigned only once.
- Method: subclasses can't override it.
- Class: can't be subclassed (
String,Integer).
A final reference to a mutable object still allows the object to change.
Q8What is composition and why is it often preferred to inheritance?intermediate
Composition means building a class from other objects it holds as fields (has-a). It keeps classes loosely coupled: you can swap the part, combine behaviours, and avoid breaking subclasses when a parent changes (the fragile base class problem). Inheritance fits only true is-a relationships.
Q9How do you make a class immutable?intermediate
- Make the class
final(or the constructor private with factories). - Make all fields
private final. - No setters.
- Defensively copy mutable inputs in the constructor and mutable outputs in getters.
- Or use a
recordwith immutable field types.
Quick check
0 of 4 answered