Object-Oriented Programming (OOP) is one of the central programming concepts in Java. Instead of organizing an application only as a sequence of instructions, Java allows you to model a program using classes and objects.
A class defines the structure and behavior of a type, while an object is an instance of that type. Classes can contain data in the form of fields and behavior in the form of methods. As applications grow, OOP helps developers organize related data and behavior, establish boundaries, reuse code, and represent relationships between different parts of a system.
What Is Object-Oriented Programming?
Object-oriented programming is a way of designing software around objects that represent
data and behavior. For example, an e-commerce application might contain concepts such as
User,
Product,
Order, and
Payment.
Each concept can have data that describes its current state and methods that define operations it can perform.
Product
|
+-- name
+-- price
+-- stock
|
+-- updateStock()
+-- calculatePrice()
This relationship between state and behavior is one of the fundamental ideas behind object-oriented design.
Class vs Object
A class is a definition or blueprint for a type. An object is an actual instance created from that class.
Class
Defines what data and behavior objects of the type can have.
Object
A runtime instance of a class with its own state.
public class Car {
String brand;
int speed;
public void drive() {
System.out.println("Car is driving");
}
}
The Car class defines two fields and one method.
Creating an object gives you an actual instance that can hold its own field values.
Car myCar = new Car();
myCar.brand = "Tesla";
myCar.speed = 120;
System.out.println(myCar.brand);
myCar.drive();
Fields and Object State
Fields are variables declared inside a class. They represent information that belongs to an object or, when declared static, to the class itself.
public class Student {
String name;
int age;
double marks;
}
Different objects created from the same class can have different field values:
Student firstStudent = new Student();
firstStudent.name = "Alice";
firstStudent.age = 21;
firstStudent.marks = 89.5;
Student secondStudent = new Student();
secondStudent.name = "Bob";
secondStudent.age = 23;
secondStudent.marks = 76.0;
Both objects follow the same class definition, but each instance has its own state. This is one of the main advantages of creating objects from reusable class definitions.
Methods and Object Behavior
Methods define behavior inside a class. Instead of changing fields directly everywhere, an object can expose methods that perform meaningful operations.
public class BankAccount {
double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
}
}
}
The methods provide operations that change the object's state. The class therefore combines the data and the operations related to that data.
Constructors
A constructor is used when creating an object and can initialize its state. A constructor has the same name as the class and does not declare a return type.
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
The object can then be created with the required initial information:
User user = new User("Alice", 25);
Constructors are especially useful when an object should begin life in a valid and meaningful state.
The this Keyword
The this keyword refers to the current object.
It is commonly used when constructor or method parameters have the same names as fields.
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
}
In this.name = name, the left side refers to
the object's field, while the right side refers to the constructor parameter.
Encapsulation
Encapsulation means controlling access to an object's internal state and exposing a controlled interface for working with it. A common Java approach is to make fields private and provide methods that enforce rules around those fields.
public class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
Code using the object does not need direct access to the internal
balance field.
Instead, it uses the public operations provided by the class.
Encapsulation is not simply about generating getters and setters for every field. Good encapsulation means designing a useful public API and keeping implementation details hidden where they do not need to be exposed.
Inheritance
Inheritance allows one class to extend another class. The child class inherits accessible members from the parent and can add its own behavior.
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
A Dog object can use behavior inherited from Animal as well as its own behavior:
Dog dog = new Dog();
dog.eat();
dog.bark();
Inheritance should represent a meaningful "is-a" relationship. It should not be used simply because one class happens to share some code with another. Composition is often a better choice when the relationship is "has-a".
Polymorphism
Polymorphism allows code to work with different object types through a common type or interface. One common example is method overriding, where a child class provides its own implementation of inherited behavior.
class Animal {
public void makeSound() {
System.out.println("Some animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
A variable of the parent type can refer to different child objects:
Animal first = new Dog();
Animal second = new Cat();
first.makeSound();
second.makeSound();
The method that executes depends on the actual object at runtime. This allows a common abstraction to work with multiple implementations.
Method Overloading vs Overriding
Both concepts are related to method behavior, but they solve different problems.
| Overloading | Overriding |
|---|---|
| Usually occurs within the same class. | Occurs when a subclass provides a new implementation of inherited behavior. |
| Same method name with different parameter lists. | Same method contract being reimplemented by a subclass. |
| Resolved using the method arguments at compile time. | Supports runtime polymorphic behavior. |
Abstraction
Abstraction focuses on exposing the important behavior of a type while hiding implementation details. Java supports abstraction through abstract classes and interfaces.
abstract class Payment {
public abstract void pay(double amount);
public void printReceipt() {
System.out.println("Receipt generated");
}
}
A concrete subclass can implement the abstract operation:
class CardPayment extends Payment {
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using card");
}
}
The rest of the application can work with the abstraction without needing to know every implementation detail of card payment processing.
The Four Commonly Taught OOP Principles
Encapsulation
Controls access to internal state and groups data with the operations that manage it.
Inheritance
Allows a class to extend another class and reuse its accessible behavior.
Polymorphism
Allows common abstractions to work with different implementations.
Abstraction
Exposes important capabilities while hiding unnecessary implementation details.
Composition: "Has-a" Relationships
OOP is not limited to inheritance. Another important design technique is composition, where an object contains or uses another object.
For example, a Car can have an Engine:
class Engine {
public void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void start() {
engine.start();
System.out.println("Car started");
}
}
A Car is not an Engine, so inheritance would not naturally model this relationship. Composition allows the Car to use an Engine without making the two types part of the same inheritance hierarchy.
Access Modifiers in OOP
Access modifiers help define which parts of a class can be used from other code. This is particularly important when designing an encapsulated class.
| Modifier | General Meaning |
|---|---|
| private | Accessible only within the declaring class. |
| protected | Accessible according to package and inheritance rules. |
| public | Accessible from code that can access the type. |
| package-private | Accessible within the same package. |
Good object-oriented design usually exposes only what callers need and keeps implementation details as restricted as practical.
Object References
A variable containing an object type stores a reference to an object rather than the complete object value directly in the way a primitive variable stores its value.
Car car = new Car();
Car anotherCar = car;
Both variables can refer to the same object. Therefore, changing the object through one reference can be observable through the other reference.
class Car {
String brand;
}
Car first = new Car();
first.brand = "Tesla";
Car second = first;
second.brand = "Toyota";
System.out.println(first.brand); // Toyota
Understanding references is essential when working with objects, method parameters, collections, inheritance, and null values.
Null References
A reference variable can contain null,
which means it is not currently referring to an object.
Car car = null;
Attempting to call an instance method or access an instance field through a null reference
can result in a NullPointerException.
Car car = null;
// Causes NullPointerException
car.drive();
Avoiding unnecessary null states and validating references at appropriate boundaries can make object-oriented code more reliable.
Designing a Class Around Responsibility
A good class should represent a meaningful concept and contain behavior that belongs naturally to that concept. Avoid creating classes that simply store unrelated fields or combine many unrelated responsibilities.
For example, an Order class could contain order information and operations directly related to the order:
public class Order {
private double subtotal;
public Order(double subtotal) {
this.subtotal = subtotal;
}
public double calculateDiscount() {
if (subtotal >= 100) {
return subtotal * 0.10;
}
return 0;
}
public double calculateTotal() {
return subtotal - calculateDiscount();
}
}
The class has a focused responsibility: representing an order and calculating values derived from that order.
Favor Behavior Over Uncontrolled Data Access
A common beginner approach is to make every field public and let other classes modify the object's state directly. Although this may work for small examples, it can make business rules difficult to protect.
public class BankAccount {
private double balance;
public void withdraw(double amount) {
if (amount <= 0) {
return;
}
if (amount > balance) {
return;
}
balance -= amount;
}
}
The class can enforce rules inside its methods instead of forcing every caller to understand how the internal state should be changed.
Interfaces and OOP Design
Interfaces provide another important mechanism for abstraction and polymorphism. An interface describes behavior that implementing classes agree to provide.
interface NotificationSender {
void send(String message);
}
class EmailNotificationSender implements NotificationSender {
@Override
public void send(String message) {
System.out.println("Sending email: " + message);
}
}
class SmsNotificationSender implements NotificationSender {
@Override
public void send(String message) {
System.out.println("Sending SMS: " + message);
}
}
Code can depend on the interface instead of being tightly coupled to one implementation. This makes it easier to replace or add implementations later.
A Practical OOP Example
Consider a simple payment model. A common payment abstraction can define the operation, while different payment implementations provide their own behavior.
interface PaymentMethod {
void pay(double amount);
}
class CardPayment implements PaymentMethod {
@Override
public void pay(double amount) {
System.out.println("Card payment: " + amount);
}
}
class UpiPayment implements PaymentMethod {
@Override
public void pay(double amount) {
System.out.println("UPI payment: " + amount);
}
}
public class PaymentDemo {
public static void main(String[] args) {
PaymentMethod payment = new CardPayment();
payment.pay(1500);
payment = new UpiPayment();
payment.pay(800);
}
}
This example combines several OOP ideas. The interface defines an abstraction, the concrete classes provide different implementations, and polymorphism allows the same reference type to work with both payment implementations.
Common OOP Mistakes in Java
Making Every Field Public
Public fields expose internal state directly and make it difficult for the class to enforce rules around changes.
Using Inheritance Only for Code Reuse
Inheritance should represent a meaningful relationship. When the relationship is primarily "has-a", composition is often more appropriate.
Creating Huge Classes
A class responsible for database access, validation, business rules, formatting, notifications, and unrelated tasks becomes difficult to maintain.
Deep Inheritance Hierarchies
Very deep inheritance trees can make behavior difficult to trace. Prefer simple relationships and composition where appropriate.
Confusing Class and Object
A class defines a type, while an object is a runtime instance of that type. Keeping this distinction clear makes the rest of OOP easier to understand.
Ignoring Object State
Methods should preserve the class's invariants and prevent invalid state whenever the object has rules that must always remain true.
Class Design Checklist
- Does the class represent one clear concept?
- Are fields protected from unnecessary external modification?
- Do methods represent meaningful behavior?
- Does the constructor establish a valid initial state?
- Is inheritance representing a genuine relationship?
- Would composition provide a simpler design?
- Could an interface provide a useful abstraction?
- Is the class becoming responsible for too many unrelated operations?
Java OOP Design Flow
Identify the concept
|
v
Create class
|
+------> Define state
| |
| +-- fields
|
+------> Define behavior
| |
| +-- methods
|
+------> Define creation
| |
| +-- constructors
|
v
Control access to state
|
v
Choose relationships
|
+-- inheritance
+-- composition
+-- interfaces
|
v
Create objects and use behavior
This process provides a practical way to move from a problem domain to an object-oriented implementation without immediately creating unnecessary classes or inheritance structures.
Java OOP: Key Takeaways
- A class defines a type containing data and behavior.
- An object is a runtime instance of a class.
- Fields represent object state.
- Methods represent object behavior.
- Constructors initialize objects when they are created.
- Encapsulation controls how object state is accessed and changed.
- Inheritance allows one class to extend another.
- Polymorphism allows common types to work with different implementations.
- Abstraction hides unnecessary implementation details behind useful contracts.
- Composition models "has-a" relationships between objects.
- Interfaces are useful for abstraction and flexible polymorphic designs.
- Good OOP design focuses on clear responsibilities rather than creating classes for everything.
Summary
Object-oriented programming gives Java developers a structured way to model software using classes and objects. Classes define state and behavior, while objects represent concrete instances that can interact with one another.
The most important OOP concepts include encapsulation, inheritance, polymorphism, and abstraction. Java also relies heavily on constructors, access modifiers, interfaces, and composition when building maintainable applications.
The goal of OOP is not simply to turn every concept into a class. Good object-oriented design creates clear responsibilities, protects important state, models meaningful relationships, and exposes behavior through well-designed interfaces. These principles become especially valuable as Java applications grow from small programs into larger systems.