Java Notes
A comprehensive introduction to Object-Oriented Programming in Java — the four pillars, paradigm comparison, real-world modeling, and why OOP dominates enterprise software development.
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data (objects) rather than functions and logic. It models real-world entities as objects that contain both state (fields) and behavior (methods), and interact with each other through well-defined interfaces.
Java is a purely object-oriented language — every piece of code you write lives inside a class. Understanding OOP isn't optional in Java; it's the foundation everything else is built upon.
What is a Programming Paradigm?
A programming paradigm is a style or approach to solving problems with code. Think of it as a mental model that guides how you structure your program.
| Paradigm | Core Idea | Languages |
|---|---|---|
| Procedural | Step-by-step instructions | C, Pascal, BASIC |
| Object-Oriented | Objects with state + behavior | Java, C++, C#, Python |
| Functional | Pure functions, immutable data | Haskell, Scala, Clojure |
| Logic | Rules and facts | Prolog |
Most modern languages support multiple paradigms. Java is primarily OOP but added functional features (lambdas) in Java 8.
Why OOP Was Invented
In the 1960s-70s, programs were getting larger and harder to maintain. Procedural code had serious problems:
Problems with this approach:
- Data and functions are separate — any function can modify any data
- Adding a new field means changing arrays AND all functions
- No way to enforce rules (e.g., age must be positive)
- Code becomes spaghetti as the project grows
OOP solution — bundle data with its behavior:
Now data is protected. Behavior is attached. Rules are enforced.
The Four Pillars of OOP
These are the four fundamental principles that define Object-Oriented Programming:
1. Encapsulation — Hide the Internals
Encapsulation means bundling data and methods together, and restricting direct access to the internal state. You expose only what's necessary through public methods.
public class BankAccount {
private double balance; // Hidden from outside
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Controlled access
}
}
public double getBalance() {
return balance; // Read-only access
}
}Analogy: A car's engine is encapsulated under the hood. You interact through the steering wheel and pedals, not by directly manipulating pistons.
2. Abstraction — Show Only What Matters
Abstraction means hiding complex implementation details and showing only the essential features. Users of your class don't need to know HOW it works internally.
// User sees this simple interface
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}
// Complex implementation is hidden
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius; // User doesn't care about the formula
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
}Analogy: When you use a TV remote, you press "Volume Up." You don't need to know about infrared signals, circuits, or speaker amplification.
3. Inheritance — Reuse and Extend
Inheritance allows a class to acquire the properties and behaviors of another class. It creates an "is-a" relationship and promotes code reuse.
public class Animal {
protected String name;
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
public class Dog extends Animal {
public Dog(String name) {
this.name = name;
}
public void bark() {
System.out.println(name + " says: Woof!");
}
}// Dog inherits eat() and sleep() from Animal, plus adds bark()
Dog dog = new Dog("Buddy");
dog.eat(); // Buddy is eating (inherited)
dog.bark(); // Buddy says: Woof! (own method)4. Polymorphism — One Interface, Many Forms
Polymorphism means the same method call can behave differently depending on the actual object type. It's the power to write flexible, extensible code.
public class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
// Polymorphism in action
Animal[] animals = { new Cat(), new Dog(), new Cat() };
for (Animal a : animals) {
a.makeSound(); // Each calls its own version
}Meow! Woof! Meow!
How Java Implements OOP
Java provides specific language features for each pillar:
| OOP Pillar | Java Feature |
|---|---|
| Encapsulation | Access modifiers (private, protected, public) |
| Abstraction | Abstract classes, Interfaces |
| Inheritance | extends keyword, super keyword |
| Polymorphism | Method overriding, Method overloading |
Everything is an Object (Almost)
In Java, everything revolves around classes and objects:
public class HelloWorld {
public static void main(String[] args) {
// Even main() lives inside a class
String message = "Hello"; // String is an object
System.out.println(message.length()); // Calling method on object
}
}5
The only non-objects in Java are the 8 primitive types: byte, short, int, long, float, double, char, boolean. Everything else is an object.
Procedural vs Object-Oriented: A Complete Example
Let's model a library system both ways:
Procedural Approach
Problems: No validation, data exposed, hard to add features (e.g., due dates, member tracking).
OOP Approach
// Usage
Library library = new Library();
library.addBook(new Book("Clean Code", "Robert Martin"));
library.addBook(new Book("Effective Java", "Joshua Bloch"));
library.printCatalog();
// Output:
Clean Code by Robert Martin [Available]
Effective Java by Joshua Bloch [Available]Key OOP Terminology
| Term | Meaning | Example |
|---|---|---|
| Class | Blueprint/template for objects | class Car { } |
| Object | Instance of a class | new Car() |
| Field/Attribute | Data stored in an object | private int speed; |
| Method | Behavior/action of an object | public void accelerate() |
| Constructor | Special method to create objects | public Car(String model) |
| Instance | A specific object created from a class | Car myCar = new Car("Tesla") |
| State | Current values of an object's fields | speed=60, fuel=80 |
| Behavior | What an object can do (its methods) | accelerate(), brake() |
Real-World Modeling with OOP
OOP excels because the real world is full of objects:
// Real-world: E-commerce system
public class Product {
private String name;
private double price;
private int stock;
// ... behavior: applyDiscount(), restock()
}
public class Customer {
private String name;
private String email;
private ShoppingCart cart;
// ... behavior: addToCart(), checkout()
}
public class Order {
private Customer customer;
private List<Product> items;
private Date orderDate;
// ... behavior: calculateTotal(), ship()
}Each class maps directly to a real concept. Relationships between classes mirror real relationships.
Advantages of OOP
- Modularity — Each object is self-contained, easier to debug
- Reusability — Inheritance and composition let you reuse code
- Flexibility — Polymorphism lets you extend without modifying existing code
- Maintainability — Changes in one class don't ripple through the entire system
- Modeling — Natural mapping between real-world entities and code
- Team Development — Different developers can work on different classes
When NOT to Use OOP
OOP isn't always the best choice:
- Simple scripts — A 20-line utility doesn't need classes
- Performance-critical code — Object creation has overhead
- Pure data transformation — Functional programming may be cleaner
- Stateless operations — When there's no state to encapsulate
Common Mistakes
- Creating classes with only getters/setters — That's just a data container, not real OOP. Add behavior!
- God classes — One class doing everything. Split responsibilities.
- Deep inheritance hierarchies — Prefer composition over inheritance when relationships are complex.
- Ignoring access modifiers — Making everything
publicdefeats encapsulation. - Confusing "has-a" with "is-a" — A Car HAS an Engine (composition). A Car IS NOT an Engine.
Best Practices
- Single Responsibility — Each class should have one reason to change
- Favor composition over inheritance — "Has-a" is often better than "is-a"
- Program to interfaces — Depend on abstractions, not concrete classes
- Keep classes small — If a class has 50+ methods, it's doing too much
- Meaningful names —
CustomerOrderProcessornotCOP
Interview Questions
Q1: What is OOP? OOP is a programming paradigm that organizes code around objects — entities that combine state (data) and behavior (methods). It's based on four principles: encapsulation, abstraction, inheritance, and polymorphism.
Q2: What are the four pillars of OOP?
- Encapsulation — bundling data and methods, hiding internals
- Abstraction — showing only essential features, hiding complexity
- Inheritance — acquiring properties from a parent class
- Polymorphism — same interface, different implementations
Q3: Why is Java not 100% object-oriented? Because Java has 8 primitive types (int, double, boolean, etc.) that are not objects. A 100% OOP language like Ruby treats everything as an object.
Q4: What's the difference between a class and an object? A class is a blueprint (template). An object is an instance (actual thing created from the blueprint). You can create many objects from one class.
Q5: Can you have OOP without inheritance? Yes. Encapsulation, abstraction, and polymorphism (via interfaces) work without inheritance. Go language, for example, has OOP without traditional inheritance.
Q6: What is the relationship between abstraction and encapsulation? Encapsulation is the mechanism (private fields, public methods). Abstraction is the design principle (hide complexity, show simplicity). Encapsulation enables abstraction.
Q7: Explain composition vs inheritance with an example. Inheritance: class Dog extends Animal (Dog IS an Animal) Composition: class Car { private Engine engine; } (Car HAS an Engine) Use inheritance for genuine "is-a" relationships. Use composition for "has-a" — it's more flexible.
Q8: What is the difference between abstraction and encapsulation? Abstraction is a design concept — hiding "what" is unnecessary from the user (e.g., showing only drive() not engine internals). Encapsulation is the implementation mechanism — bundling data with methods and restricting access using access modifiers (private, public). Encapsulation is HOW you achieve abstraction.
Q9: Name some popular OOP languages and their features. Java (pure OOP, platform-independent), C++ (supports both procedural and OOP), Python (multi-paradigm with OOP support), C# (.NET-based OOP), Ruby (everything is an object). Java enforces OOP most strictly — you cannot write code outside a class.
Q10: What is the SOLID principle in OOP? SOLID stands for: Single Responsibility (one class, one job), Open/Closed (open for extension, closed for modification), Liskov Substitution (subtypes must be substitutable for base types), Interface Segregation (many specific interfaces over one general), Dependency Inversion (depend on abstractions, not concretions).
Q11: What is coupling and cohesion in OOP? Coupling refers to how much one class depends on another — low coupling is preferred. Cohesion refers to how related the methods and data within a class are — high cohesion is preferred. Good OOP design aims for low coupling and high cohesion.
Q12: Can OOP and functional programming coexist? Yes. Java 8+ supports functional programming with lambdas, streams, and functional interfaces alongside OOP. You can use functional style for data processing while using OOP for domain modeling. Modern Java encourages combining both paradigms.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for OOPs Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, oops, introduction, oops introduction
Related Java Master Course Topics