Object-oriented concepts
Core object-oriented concepts in Java: class, object, abstraction, encapsulation, inheritance, polymorphism, associations (aggregation/composition), access control, cohesion/coupling, and basic UML notations.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Object-oriented concepts help you design large, maintainable Java systems by organizing code around real-world entities with clear responsibilities. Engineers use these ideas daily to model domains, reduce coupling, increase reuse, and enable testing and evolution of software over time.
Key ideas
- Class: A blueprint for creating objects. Exact definition: A class defines the structure (fields), behavior (methods), and construction (constructors) common to its instances.
- Identity, state, behavior: Identity distinguishes one object from another; state is the data stored in fields; behavior is what the object can do via methods.
- Abstraction: Exact definition: Abstraction is the process of modeling essential characteristics of an entity while ignoring irrelevant details for a given context. Assumption: the model faithfully captures required properties for its intended use.
- Encapsulation: Exact definition: Encapsulation is the bundling of data and the methods that operate on that data within a single unit (class), restricting direct access to some of the object’s components.
- Information hiding: Exact definition: Information hiding is the practice of concealing implementation details behind a stable interface so that clients depend only on what is guaranteed, not how it is done. In Java, private fields with public getters/setters are a common mechanism.
- Interface (software contract): Exact definition: An interface specifies a set of operations (method signatures) that a conforming class agrees to implement, without prescribing the implementation. Note: Interfaces may also declare constants (public static final fields) and default/static methods (since Java 8).
- Abstract class: Exact definition: An abstract class is a class that cannot be instantiated and may contain abstract methods (without bodies) alongside concrete methods and fields; it is used to share common state/behavior and define a partial implementation for subclasses.
- Constructor: Exact definition: A constructor is a special member (not a method) with the same name as the class, used to initialize new objects; it has no return type and is not inherited. Notes: If no constructor is declared, Java provides a default no-argument constructor (with the same accessibility as the class); if any constructor is declared, no default is provided.
- Message passing: Exact definition: Message passing is the invocation of a method on an object, optionally with parameters, to request it perform some operation.
- Association: Exact definition: Association is a structural relationship where one class references another. It indicates “uses/knows” relationship. Multiplicity (1, 0..1, , 1..) can be specified.
- Aggregation: Exact definition: Aggregation is a specialized association representing a whole–part relationship where the part can exist independently of the whole (shared ownership). In UML, it is shown with a hollow diamond at the whole end.
- Composition: Exact definition: Composition is a strong form of aggregation where the part’s lifecycle is bound to the whole (exclusive ownership). In UML, it is shown with a filled (black) diamond at the whole end.
- Generalization (Inheritance): Exact definition: Inheritance is a relationship where a subclass acquires the accessible members of a superclass, enabling reuse and extension. Java supports single inheritance of classes and multiple inheritance of type via interfaces.
- Polymorphism: Exact definition: Polymorphism is the ability to present the same interface for differing underlying forms (data types). Two main kinds: compile-time polymorphism (method overloading) and run-time polymorphism (method overriding + dynamic dispatch).
- Method overloading: Exact definition: Overloading is defining multiple methods in the same scope with the same name but different parameter lists. Resolution is at compile time.
- Method overriding: Exact definition: Overriding is redefining in a subclass a method from the superclass with the same signature and a covariant (compatible) return type; the overriding method cannot reduce visibility and cannot throw broader checked exceptions than the overridden method. Resolution is at run time via dynamic dispatch for instance methods.
- Dynamic binding (dynamic dispatch): Exact definition: The method implementation that is executed is determined at run time based on the actual object type, not the reference type, for non-static, non-final, non-private instance methods.
- Access control: Exact definitions of modifiers in Java:
- public: Accessible from anywhere.
- protected: Accessible within the same package and in subclasses (even in different packages via inheritance).
- (package-private/default): No modifier. Accessible only within the same package.
- private: Accessible only within the declaring class.
- Cohesion: Exact definition: Cohesion is the degree to which the elements inside a module/class belong together. High cohesion is desired.
- Coupling: Exact definition: Coupling is the degree of interdependence between modules/classes. Low coupling is desired.
- Liskov Substitution Principle (LSP): Exact statement: Let φ(x) be a property provable about objects x of type T. Then φ(y) should be true for objects y of subtype S of T. Informally: Objects of a superclass should be replaceable with objects of its subclass without breaking program correctness. Assumptions: Clients rely only on the superclass’s specified behavior.
- Open/Closed Principle (OCP): Exact statement: Software entities should be open for extension, but closed for modification. In Java, prefer adding new subclasses or implementations over changing tested base code.
Typical diagram to draw in exams (describe exactly):
- UML class diagram for a library system:
- Draw three boxes labeled: Book, Member, Library.
- Inside Book: fields (title:String, author:String); methods (getTitle():String, getAuthor():String).
- Inside Member: fields (name:String); methods (borrow(b:Book):void, returnBook(b:Book):void).
- Inside Library: fields (books: List<Book>, members: List<Member>); methods (addBook(b:Book):void, register(m:Member):void).
- Draw associations:
- Library —(hollow diamond at Library)— Book with multiplicity Library 1, Book 0..* (aggregation).
- Library —(hollow diamond at Library)— Member with multiplicity Library 1, Member 0..* (aggregation).
- Optionally generalize: PhysicalBook and EBook inherit from Book via a generalization arrow (empty triangle pointing to Book).
- Label multiplicities near association ends as: 1, 0..*, etc.
Derivation often asked: Choosing aggregation vs composition
- Step 1: Identify lifecycle dependency: If part cannot logically exist without whole (e.g., Engine within Car), choose composition.
- Step 2: Identify sharing: If part can belong to multiple wholes or live independently (e.g., Employee and Department), choose aggregation.
- Step 3: Reflect this in UML: filled diamond for composition, hollow diamond for aggregation.
Formulas
Basic class declaration.
ClassName obj = new ClassName(args);Object creation using a constructor.private Type field; public Type getField() { return field; } public void setField(Type x) { this.field = x; }Encapsulation with getters/setters.public class Sub extends Super { /* overrides */ }Inheritance (single inheritance of classes in Java).public interface I { returnType op(params); } class C implements I { public returnType op(params) { /* ... */ } }Interface and its implementation.@Override public returnType method(params) { /* overriding */ }Overriding annotation to catch signature mistakes.public void m(int x); public void m(double x);Overloading by parameter list.super(params)andsuper.method(params)Calling superclass constructor/method. Note:super(params)must be the first statement in a constructor.public • protected • (package-private) • privateAccess modifiers and their reach.final class/field/methodfinal class: no subclass; final field: value cannot be reassigned after initialization (for reference types, the reference is final but the object may still be mutable); final method: cannot be overridden.List<Part> parts = new ArrayList<>();Typical collection field to model association/aggregation.
Worked examples
Example 1: Encapsulation with a bank account Complete Java program:
import java.util.Locale;
class BankAccount {
private final String owner;
private double balance;
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
}
public String getOwner() { return owner; }
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be > 0");
balance += amount;
}
public void withdraw(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be > 0");
if (amount > balance) throw new IllegalArgumentException("insufficient funds");
balance -= amount;
}
@Override
public String toString() {
return String.format(Locale.ROOT, "BankAccount{owner='%s', balance=%.2f}", owner, balance);
}
}
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.ROOT);
BankAccount a = new BankAccount("Asha", 1000.0);
a.deposit(500.0);
System.out.printf("After deposit: %.2f\n", a.getBalance());
a.withdraw(200.0);
System.out.printf("After withdraw: %.2f\n", a.getBalance());
System.out.println(a);
}
}
Sample input: (none) Exact output:
After deposit: 1500.00
After withdraw: 1300.00
BankAccount{owner='Asha', balance=1300.00}
What it shows: Private fields and public methods enforce valid state changes; toString provides a readable representation.
Example 2: Polymorphism with a Shape interface Complete Java program:
import java.util.Locale;
interface Shape {
String name();
double area();
}
class Circle implements Shape {
private final double r;
public Circle(double r) { this.r = r; }
public String name() { return "Circle"; }
public double area() { return Math.PI * r * r; }
}
class Rectangle implements Shape {
private final double w, h;
public Rectangle(double w, double h) { this.w = w; this.h = h; }
public String name() { return "Rectangle"; }
public double area() { return w * h; }
}
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.ROOT);
Shape[] shapes = { new Circle(3.0), new Rectangle(4.0, 5.0) };
for (Shape s : shapes) {
System.out.printf("%s area = %.2f\n", s.name(), s.area());
}
}
}
Sample input: (none) Exact output:
Circle area = 28.27
Rectangle area = 20.00
What it shows: The same interface variable (Shape) can refer to different concrete objects; the correct area() is chosen at run time (dynamic dispatch).
Example 3: Association, aggregation, and composition Complete Java program:
import java.util.*;
class Employee {
private final String name;
public Employee(String name) { this.name = name; }
public String getName() { return name; }
@Override public String toString() { return name; }
}
// Aggregation: Department has Employees, but Employees can exist independently
class Department {
private final String name;
private final List<Employee> employees = new ArrayList<>();
public Department(String name) { this.name = name; }
public void addEmployee(Employee e) { employees.add(e); }
public List<Employee> getEmployees() { return Collections.unmodifiableList(employees); }
@Override public String toString() { return name; }
}
// Composition: Car owns an Engine; Engine's lifecycle is bound to Car
class Engine {
private final String model;
public Engine(String model) { this.model = model; }
public String start() { return "Engine " + model + " started"; }
}
class Car {
private final String model;
private final Engine engine; // composed part
public Car(String model) {
this.model = model;
this.engine = new Engine(model + "-ENG");
}
public String start() { return "Car " + model + ": " + engine.start(); }
}
// Simple association: Project uses Employee temporarily
class Project {
private final String code;
public Project(String code) { this.code = code; }
public String assign(Employee e) {
return "Project " + code + " assigned to " + e.getName();
}
}
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee("Ravi");
Employee e2 = new Employee("Meera");
Department cse = new Department("CSE");
cse.addEmployee(e1);
cse.addEmployee(e2);
System.out.println("Department: " + cse);
System.out.println("Employees: " + cse.getEmployees());
Car car = new Car("Sedan");
System.out.println(car.start());
Project p = new Project("LIBSYS");
System.out.println(p.assign(e2));
}
}
Sample input: (none) Exact output:
Department: CSE
Employees: [Ravi, Meera]
Car Sedan: Engine Sedan-ENG started
Project LIBSYS assigned to Meera
What it shows: Aggregation (Department–Employee), composition (Car–Engine), and a simple association (Project–Employee) in code.
Common mistakes
- Saying “Java supports multiple inheritance of classes.” Correction: Java supports single inheritance of classes, multiple inheritance of type via interfaces.
- Writing public fields “for simplicity” in examples and then claiming encapsulation. Encapsulation requires restricted access and behavior-controlled updates.
- Overriding with a changed parameter list (actually overloading), or changing return type incompatibly. Use @Override to detect mistakes.
- Assuming access modifiers: forgetting that default (no modifier) is package-private, not “public inside package” or “protected”.
- Expecting dynamic dispatch for static, private, or final methods. These are not polymorphic instance methods.
- Forgetting to set a fixed Locale or formatting when asserting exact numeric output in answers; commas/decimals can differ by locale.
- Drawing UML associations without multiplicities or incorrect diamond placement for aggregation/composition.
- Expecting fields to be polymorphic: field access is resolved by the reference type (hiding), not dynamically dispatched like instance methods.
For your exam
- Short notes: difference between overloading and overriding; interface vs abstract class; aggregation vs composition with UML notation. Include a neat labeled sketch (describe multiplicities and diamonds) and 2–3 bullet differences.
- Diagrams: UML class diagram for a mini domain (e.g., Library, Hospital). Include classes with fields/methods, associations with multiplicities, correct diamonds/triangles, and labels.
- Programs: small Java classes demonstrating encapsulation and polymorphism. Ensure code compiles, includes main, prints output exactly as required, and you explain which concept appears where in code.
- Reasoning: choosing abstraction boundaries; applying SOLID (especially LSP and OCP) in a scenario. State principle, assumptions, and justify design choices.
- Compare/contrast: cohesion vs coupling; composition vs inheritance. Provide definitions, pros/cons, and when to use which.
Answer structure tips:
- Start with exact definition, then a simple example, then one diagram or snippet, then one implication/benefit.
- Use consistent naming and show multiplicities (1, 0.., 1..) on diagrams.
- For code, prefer small, clear classes and print statements that prove behavior.
Quick check
- Define encapsulation and show one Java syntax element that implements it.
- Distinguish aggregation from composition in one sentence each, and give one example of each.
- What does Liskov Substitution Principle require, and how does Java support it at run time?
Answers: 1) Encapsulation is bundling data with methods and restricting direct access; Java implements it with private fields and public methods (getters/setters). 2) Aggregation: whole–part where part can exist independently (Department–Employee); Composition: whole–part where part’s lifecycle depends on whole (Car–Engine). 3) LSP requires subtype objects can replace supertype objects without breaking correctness; Java supports this with inheritance and dynamic method dispatch on overridden instance methods.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?