OOP in Java
7 pages · ~5 min✓ Reviewed
Start here. Next up: Collections Framework.
Classes and Objects Mental Model
1. Class, Object, Reference
- Class = blueprint;
newbuilds an object on the heap - The variable holds a reference, not the object
b = acopies the reference: both point to one object==compares references
java
Dog a = new Dog("Rex"); Dog b = a; b.name = "Max"; System.out.println(a.name); System.out.println(a == b);
one object, two references
output
Max true
2. Defaults and this
| Default | Unassigned use | |
|---|---|---|
| Field | 0, false, null | OK |
| Local | none | compile error |
this= the current objectthis.name = nameresolves name shadowingthis(...)chains to another constructor
Common mistake
== on objects asks "same reference?", not "same state?". Use equals for state.
3. Interview Point
- Class vs object? Class is the blueprint; an object is one instance of it.
- Where do objects live? On the heap; variables hold references.
- What does
==compare? References, not state. - Field vs local defaults? Fields get 0, false, null; locals get none.
Constructors and Initialization Order
1. Constructor Rules
- Same name as the class, no return type
- Write none: compiler adds a default no-arg constructor
- Write any: default is gone,
new Foo()fails unless declared - Explicit
super(...)/this(...)first (Java 25 allows a prologue that does not touchthis) - Implicit
super()fails if parent has no no-arg constructor
2. Initialization Order
- 1Static blocksonce, at class load
- 2Parent fields + blocks
- 3Parent constructor
- 4Child fields + blocks
- 5Child constructor
3. Overridable Call Bug
- Parent constructor calls overridable method: child override runs before child fields are set
java
class P { P() { show(); } void show() {} } class C extends P { String s = "hi"; void show() { System.out.println(s); } } new C();
s is still null when show() runs
output
null
Access Modifiers, static and final
1. Visibility, widest to narrowest
| Modifier | Reach |
|---|---|
public | everywhere |
protected | same package + subclasses |
| package-private | same package (no keyword) |
private | same class only |
2. static and final
static= class-level: shared by all objects, used asClassName.member- A static method has no
thisand no direct instance fields finalvariable: assigned once; a final reference can still have its object mutatedfinalmethod: no override.finalclass: no extend (String)staticmethods are hidden, not overridden- Constants:
public static final, UPPER_CASE; a static block runs once at class load
java
final List<String> xs = new ArrayList<>(); xs.add("a"); // OK: object mutated xs = null; // error: reassigned
final locks the reference
3. Interview Point
- protected vs package-private? protected also reaches subclasses in other packages
- final means immutable? No, only the reference is fixed
- Override a static method? No, it is hidden; the declared type decides
- Why is String final? Safe immutability: string pool, hash keys, security
Inheritance, Abstract Classes and Interfaces
1. extends and super
extends: single class inheritancesuper.m()calls the parent versionsuper(...)calls the parent constructor (Java 25: a prologue not using this may precede)- private members are not inherited
2. Abstract class vs interface
| Abstract class | Interface | |
|---|---|---|
| State | fields allowed | constants only |
| Constructors | yes | no |
| Per class | extends one | implements many |
| Methods | abstract + concrete | abstract; default, static (Java 8) |
| Pick for | shared state, is-a family | capability, unrelated classes |
- Abstract class cannot be instantiated
3. Diamond problem
java
interface A { default void m() {} }
interface B { default void m() {} }
class C implements A, B {
public void m() { A.super.m(); }
}C must override m()
Same default twice
Class must override; pick one with A.super.m()
4. Interview Point
- Abstract vs interface? Shared state and code: abstract; capability: interface
- Why one parent class? Ambiguous state and constructors; interfaces carry none
- Abstract constructor? Yes, run via
super(...) - Interface method body? Yes:
defaultorstatic
Overloading vs Overriding and equals/hashCode
1. Overloading vs Overriding
| Overloading | Overriding | |
|---|---|---|
| Signature | same name, different params | same signature, subclass |
| Resolved | compile time, declared types | runtime, actual object (dynamic dispatch) |
| Return type | alone is not enough | may be covariant |
- Always add
@Override - Access cannot be narrowed
- No broader checked exceptions
2. equals and hashCode
java
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
P p = (P) o;
return id == p.id && Objects.equals(name, p.name); }
@Override public int hashCode() {
return Objects.hash(id, name); }same fields in both
- Default
equalsis reference equality (==) - Equal objects → same hashCode
- Same hashCode does not mean equal
- hashCode is stable across calls
3. Mistakes and Interview Point
equalswithouthashCode: key lands in another bucket,HashMapmisses it- Mutable fields in a key's hash
equals(Point p)only overloads, never overrides
- Compile-time? Overloading
- Contract? equal → same hashCode
- Only equals? HashMap/HashSet lookups fail
- Wrong param type? It overloads;
@Overridecatches it
Java OOP Cheat Sheet
1. Modifiers and Keywords
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
private | yes | no | no | no |
| package-private | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
static: class-level, sharedfinalvariable: no reassignfinalmethod: no overridefinalclass: no extendabstract: no instantiate
2. Abstract vs Interface, Overload vs Override
| Abstract class | Interface | |
|---|---|---|
| State | fields | constants only |
| Constructors | yes | no |
| Multiple inheritance | one | many |
| Default methods | concrete methods | default |
| Use case | shared is-a base | capability |
- Overloading: compile time, by declared types
- Overriding: runtime, by actual object
- Always add
@Override
3. equals / hashCode
- this == o
- Class check
- Cast
- Objects.equals fields
hashCode:Objects.hashof the same fields- Override both or neither
Interview Point
Two rules? equal objects ⇒ same hash; hash stable across calls. Init order? static → parent fields → parent ctor → child fields → child ctor. Illegal? abstract + final, abstract + private/static.
Check yourself
Overloads f(Object) and f(String) exist. Which one does this call?
f(Object)- Overloads are chosen at compile time by the declared type, not the actual object
Object x = "hi";
f(x);What does new B() print?
0- A's constructor runs before B's fields are set, but the override still runs
class A { A() { show(); } void show() {} } class B extends A { int n = 5; void show() { System.out.println(n); } }
A class overrides equals on id but not hashCode. Does a HashSet find an equal copy of an added object?
- Usually no:
containsreturns false - Different hash codes usually land in different buckets, so
equalsnever runs