Handbooks / Java / Chapter 1

OOP in Java

7 pages · ~5 min✓ Reviewed

Start here. Next up: Collections Framework.

JavaPage 1

Classes and Objects Mental Model

1. Class, Object, Reference

  • Class = blueprint; new builds an object on the heap
  • The variable holds a reference, not the object
  • b = a copies 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

DefaultUnassigned use
Field0, false, nullOK
Localnonecompile error
  • this = the current object
  • this.name = name resolves name shadowing
  • this(...) 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.
JavaPage 2

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 touch this)
  • Implicit super() fails if parent has no no-arg constructor

2. Initialization Order

  1. 1Static blocksonce, at class load
  2. 2Parent fields + blocks
  3. 3Parent constructor
  4. 4Child fields + blocks
  5. 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
JavaPage 3

Access Modifiers, static and final

1. Visibility, widest to narrowest

ModifierReach
publiceverywhere
protectedsame package + subclasses
package-privatesame package (no keyword)
privatesame class only

2. static and final

  • static = class-level: shared by all objects, used as ClassName.member
  • A static method has no this and no direct instance fields
  • final variable: assigned once; a final reference can still have its object mutated
  • final method: no override. final class: no extend (String)
  • static methods 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
JavaPage 4

Inheritance, Abstract Classes and Interfaces

1. extends and super

  • extends: single class inheritance
  • super.m() calls the parent version
  • super(...) calls the parent constructor (Java 25: a prologue not using this may precede)
  • private members are not inherited

2. Abstract class vs interface

Abstract classInterface
Statefields allowedconstants only
Constructorsyesno
Per classextends oneimplements many
Methodsabstract + concreteabstract; default, static (Java 8)
Pick forshared state, is-a familycapability, 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: default or static
JavaPage 5

Overloading vs Overriding and equals/hashCode

1. Overloading vs Overriding

OverloadingOverriding
Signaturesame name, different paramssame signature, subclass
Resolvedcompile time, declared typesruntime, actual object (dynamic dispatch)
Return typealone is not enoughmay 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 equals is reference equality (==)
  • Equal objects → same hashCode
  • Same hashCode does not mean equal
  • hashCode is stable across calls

3. Mistakes and Interview Point

  • equals without hashCode: key lands in another bucket, HashMap misses 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; @Override catches it
JavaPage 6

Java OOP Cheat Sheet

1. Modifiers and Keywords

ModifierClassPackageSubclassWorld
privateyesnonono
package-privateyesyesnono
protectedyesyesyesno
publicyesyesyesyes
  • static: class-level, shared
  • final variable: no reassign
  • final method: no override
  • final class: no extend
  • abstract: no instantiate

2. Abstract vs Interface, Overload vs Override

Abstract classInterface
Statefieldsconstants only
Constructorsyesno
Multiple inheritanceonemany
Default methodsconcrete methodsdefault
Use caseshared is-a basecapability
  • Overloading: compile time, by declared types
  • Overriding: runtime, by actual object
  • Always add @Override

3. equals / hashCode

  1. this == o
  2. Class check
  3. Cast
  4. Objects.equals fields
  • hashCode: Objects.hash of 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.

JavaPage 7

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: contains returns false
  • Different hash codes usually land in different buckets, so equals never runs