Object-Oriented Programming in Java
April 20, 2025
Object-Oriented Programming in Java
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which contain data (attributes) and code (methods).
Core OOP Concepts
1. Classes and Objects
A class is a blueprint for creating objects. It defines a datatype by bundling data and methods that work on that data.
// Class definition
public class Car {
// Fields (attributes)
private String make;
private String model;
private int year;
// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Methods
public void startEngine() {
System.out.println("Engine started!");
}
public String getInfo() {
return year + " " + make + " " + model;
}
}
// Creating objects (instances of the class)
Car myCar = new Car("Toyota", "Corolla", 2020);
myCar.startEngine();
System.out.println(myCar.getInfo());
Class vs Object
Class
Blueprint
- Fields
- Constructors
- Methods
Object
Instance
- Actual data
- State
- Behavior
2. Encapsulation
Encapsulation is the bundling of data and methods within a single unit (class), and restricting access to some of the object’s components.
public class BankAccount {
// Private fields - encapsulated
private String accountNumber;
private double balance;
// Public methods to access and modify the private fields
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public boolean withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
}
Benefits of encapsulation:
- Data hiding: Internal representation is hidden
- Increased flexibility: Implementation can change without affecting client code
- Reusability: Encapsulated code can be reused
3. Inheritance
Inheritance is a mechanism where a new class (subclass) is derived from an existing class (superclass).
// Superclass
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
}
// Subclass
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // Call superclass constructor
this.breed = breed;
}
public void bark() {
System.out.println(name + " is barking");
}
// Override superclass method
@Override
public void eat() {
System.out.println(name + " the " + breed + " is eating dog food");
}
}
classDiagram
class Animal {
+eat()
}
class Dog {
+bark()
}
class Cat {
+meow()
}
Animal <|-- Dog
Animal <|-- Cat
Inheritance Hierarchy
4. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
// Using the Animal class from above
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void eat() {
System.out.println(name + " is eating cat food");
}
}
// Polymorphic behavior
Animal animal1 = new Dog("Buddy", "Golden Retriever");
Animal animal2 = new Cat("Whiskers");
animal1.eat(); // Calls Dog's eat method
animal2.eat(); // Calls Cat's eat method
// Array of Animals can contain Dogs and Cats
Animal[] animals = {
new Dog("Rex", "German Shepherd"),
new Cat("Felix")
};
// Polymorphic loop
for (Animal animal : animals) {
animal.eat(); // Calls the appropriate eat method
}
Abstract Classes and Interfaces
Abstract Classes
An abstract class cannot be instantiated and may contain abstract methods that must be implemented by subclasses.
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
// Abstract method - no implementation
public abstract double calculateArea();
}
public class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Interfaces
An interface contains only abstract methods and constants, allowing a class to implement multiple interfaces.
public interface Drawable {
void draw(); // Abstract method
}
public interface Resizable {
void resize(double factor); // Abstract method
}
// A class can implement multiple interfaces
public class Square extends Shape implements Drawable, Resizable {
private double side;
public Square(String color, double side) {
super(color);
this.side = side;
}
@Override
public double calculateArea() {
return side * side;
}
@Override
public void draw() {
System.out.println("Drawing a " + color + " square");
}
@Override
public void resize(double factor) {
side *= factor;
}
}
Conclusion
Object-Oriented Programming in Java provides a powerful way to structure code, making it more modular, reusable, and easier to maintain. By understanding and applying the core concepts of OOP—classes and objects, encapsulation, inheritance, and polymorphism—you can write more efficient and organized Java programs.
Remember that good OOP design follows the SOLID principles:
- Single Responsibility Principle
- Open/Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle