Notes › Java
Java OOP Concepts
Java is built around object-oriented programming: you model the problem as objects that hold data (fields) and behaviour (methods). A class is the blueprint; an object is an instance created with new.
public class Student {
private final int roll; // fields (state)
private String name;
private static int count = 0; // shared by all students
public Student(int roll, String name) { // constructor
this.roll = roll; // this = the current object
this.name = name;
count++;
}
public String getName() { return name; } // methods (behaviour)
public static int getCount() { return count; }
}
Student s = new Student(1, "Asha"); // object on the heap, reference s on the stack
Constructors
- Same name as the class, no return type, runs on
new. - If you write none, Java adds a default no-arg constructor.
- Overloaded constructors call each other with
this(...):
public Student(String name) { this(0, name); }
- A constructor can't be
static,finalorabstract, and is not inherited.
static
static members belong to the class, not to objects: one copy shared by all. Use them for counters, constants (static final) and utility methods (Math.max). A static method can't use this or instance fields directly.
The four pillars
1. Encapsulation — hide data, expose behaviour
Make fields private and provide methods that validate:
public class BankAccount {
private double balance;
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("Amount must be positive");
balance += amt;
}
public double getBalance() { return balance; } // no setter: balance can't be set directly
}
2. Inheritance — reuse with extends
class Animal {
protected String name;
Animal(String name) { this.name = name; }
void sound() { System.out.println("..."); }
}
class Dog extends Animal {
Dog(String name) { super(name); } // call the parent constructor first
@Override void sound() { System.out.println(name + " barks"); }
}
- Java supports single inheritance of classes (no
extends A, B) to avoid the diamond problem; a class can implement many interfaces. - Every class extends
Object(givestoString,equals,hashCode). super.method()calls the parent's version.
3. Polymorphism — one interface, many forms
Compile-time (overloading): same name, different parameters.
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
Runtime (overriding): a child redefines a parent method; the object's actual type decides which runs (dynamic dispatch).
Animal a = new Dog("Tommy"); // parent reference, child object
a.sound(); // "Tommy barks" — decided at runtime
| Overloading | Overriding | |
|---|---|---|
| Where | same class | parent and child |
| Parameters | must differ | must be the same |
| Return type | can differ | same or a subtype (covariant) |
| Decided | compile time | runtime |
| static / private methods | can be overloaded | can't be overridden (static methods are hidden) |
4. Abstraction — show what, hide how
abstract class Shape {
abstract double area(); // no body
void describe() { System.out.println("Area: " + area()); }
}
interface Drawable { void draw(); } // a contract
class Circle extends Shape implements Drawable {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
public void draw() { System.out.println("○"); }
}
Abstract class vs interface (Java 8+)
| Abstract class | Interface | |
|---|---|---|
| Methods | abstract and concrete | abstract, default, static, private |
| Fields | any | only public static final constants |
| Constructors | yes | no |
| Inheritance | extend one | implement many |
| Use when | classes share code and state | unrelated classes share a capability (Comparable, Runnable) |
More: Abstract Class vs Interface.
Access modifiers
| Modifier | Class | Package | Subclass | Everywhere |
|---|---|---|---|---|
private |
✅ | ❌ | ❌ | ❌ |
| default (none) | ✅ | ✅ | ❌ (other package) | ❌ |
protected |
✅ | ✅ | ✅ | ❌ |
public |
✅ | ✅ | ✅ | ✅ |
final
finalvariable → can't be reassigned (a constant).finalmethod → can't be overridden.finalclass → can't be extended (e.g.String).
equals and hashCode
== compares references; equals compares content (when overridden). If you override equals, override hashCode too — otherwise HashMap/HashSet break.
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student s)) return false;
return roll == s.roll;
}
@Override public int hashCode() { return Integer.hashCode(roll); }
Java 16+ records generate all of this: record Point(int x, int y) {}.
Composition over inheritance
"A Car has an Engine" (composition) is often better than "a Car is an Engine". Inherit only for true is-a relationships.
Interview one-liners
- Class = blueprint, object = instance; objects live on the heap.
- Overloading is compile-time polymorphism; overriding is runtime polymorphism.
- Java has no multiple inheritance of classes, but a class can implement many interfaces.
super()must be the first line of a constructor.- Override
hashCodewhenever you overrideequals. - Related: Four Pillars of OOP, Java Collections Framework.