Introduction to Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects and classes rather than functions and logic. It focuses on the objects that developers want to manipulate rather than the logic required to manipulate them.

What is OOP?

OOP is a methodology that helps in creating modular, reusable, and maintainable software by modeling real-world entities as objects that contain both data and behavior.

Key Concepts in OOP

  • Class: Blueprint or template for creating objects
  • Object: Instance of a class
  • Method: Function defined inside a class
  • Attribute: Variable defined inside a class
  • Inheritance: Mechanism to create new classes from existing ones
  • Polymorphism: Ability to take many forms
  • Encapsulation: Binding data and methods together
  • Abstraction: Hiding implementation details

Four Pillars of Object-Oriented Programming

OOP is built upon four fundamental principles that form the foundation of object-oriented design.

1. Encapsulation

Wrapping data and methods that work on data within one unit (class).

2. Inheritance

Mechanism where one class acquires the properties and behaviors of another class.

3. Polymorphism

Ability of an object to take many forms, allowing the same operation to behave differently on different classes.

4. Abstraction

Hiding complex implementation details and showing only essential features.

Exam Tip: Remember the four pillars of OOP: Encapsulation, Inheritance, Polymorphism, and Abstraction. These are frequently asked in competitive exams.

Class and Object

Classes and objects are the fundamental building blocks of object-oriented programming.

Class

A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.

// Class definition example class Student { // Attributes (data members) private String name; private int age; private double marks; // Methods (member functions) public void setDetails(String n, int a, double m) { name = n; age = a; marks = m; } public void display() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Marks: " + marks); } }

Object

An object is an instance of a class. When a class is defined, no memory is allocated until objects are created.

// Object creation and usage Student s1 = new Student(); // Creating object s1.setDetails("John", 20, 85.5); // Calling method s1.display(); // Calling method
Class Object
Blueprint or template Instance of a class
Logical entity Physical entity
Does not occupy memory Occupies memory
Declared once Can be created multiple times

Encapsulation

Encapsulation is the mechanism of wrapping data (variables) and code (methods) together as a single unit. In encapsulation, the variables of a class are hidden from other classes and can be accessed only through the methods of their current class.

How to Achieve Encapsulation

  • Declare the variables of a class as private
  • Provide public setter and getter methods to modify and view the variables
// Encapsulation example class BankAccount { // Private data members private String accountNumber; private double balance; // Public getter methods public String getAccountNumber() { return accountNumber; } public double getBalance() { return balance; } // Public setter methods public void setAccountNumber(String accNo) { accountNumber = accNo; } public void setBalance(double bal) { if (bal >= 0) { // Validation balance = bal; } } // Public method to deposit amount public void deposit(double amount) { if (amount > 0) { balance += amount; } } }

Benefits of Encapsulation

  • Data Hiding: User cannot directly access internal data
  • Increased Flexibility: Can make variables read-only or write-only
  • Reusability: Encapsulated code can be reused
  • Testing: Easy to unit test
  • Maintenance: Easy to change implementation without affecting users

Inheritance

Inheritance is a mechanism in which one class acquires the properties and behaviors of another class. The class that inherits is called the subclass or derived class, and the class being inherited from is called the superclass or base class.

Types of Inheritance

  • Single Inheritance: One class extends another class
  • Multilevel Inheritance: A class extends another class which extends another class
  • Hierarchical Inheritance: Multiple classes extend a single class
  • Multiple Inheritance: A class extends multiple classes (not supported in Java)
  • Hybrid Inheritance: Combination of two or more types of inheritance
// Single Inheritance example class Animal { // Base class void eat() { System.out.println("Eating..."); } void sleep() { System.out.println("Sleeping..."); } } class Dog extends Animal { // Derived class void bark() { System.out.println("Barking..."); } } // Using inheritance Dog d = new Dog(); d.eat(); // Inherited from Animal d.sleep(); // Inherited from Animal d.bark(); // Defined in Dog

Benefits of Inheritance

  • Code Reusability: Reuse existing code without rewriting
  • Method Overriding: Achieve runtime polymorphism
  • Extensibility: Easy to extend existing functionality
  • Data Hiding: Base class can keep some data private
Note: Java doesn't support multiple inheritance with classes to avoid complexity, but it supports multiple inheritance with interfaces.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common super class. The word polymorphism means "many forms".

Types of Polymorphism

1. Compile-time Polymorphism (Static)

Achieved through method overloading. Method overloading occurs when multiple methods have the same name but different parameters.

// Method Overloading example class Calculator { // Method with two int parameters int add(int a, int b) { return a + b; } // Method with three int parameters int add(int a, int b, int c) { return a + b + c; } // Method with double parameters double add(double a, double b) { return a + b; } }

2. Runtime Polymorphism (Dynamic)

Achieved through method overriding. Method overriding occurs when a subclass provides a specific implementation of a method that is already provided by its parent class.

// Method Overriding example class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void makeSound() { // Method overriding System.out.println("Dog barks"); } } class Cat extends Animal { void makeSound() { // Method overriding System.out.println("Cat meows"); } } // Runtime polymorphism Animal myAnimal; myAnimal = new Dog(); myAnimal.makeSound(); // Output: Dog barks myAnimal = new Cat(); myAnimal.makeSound(); // Output: Cat meows
Exam Tip: Remember that method overloading is compile-time polymorphism (same method name, different parameters), while method overriding is runtime polymorphism (same method signature in parent and child class).

Abstraction

Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. It helps to reduce programming complexity and effort.

Ways to Achieve Abstraction

  • Abstract Classes: Classes that cannot be instantiated
  • Interfaces: Blueprint of a class

Abstract Classes

// Abstract class example abstract class Shape { abstract void draw(); // Abstract method (no implementation) // Concrete method void display() { System.out.println("This is a shape"); } } class Circle extends Shape { void draw() { // Implementing abstract method System.out.println("Drawing Circle"); } } class Rectangle extends Shape { void draw() { // Implementing abstract method System.out.println("Drawing Rectangle"); } }

Interfaces

// Interface example interface Vehicle { void start(); // Abstract method void stop(); // Abstract method } class Car implements Vehicle { public void start() { System.out.println("Car started"); } public void stop() { System.out.println("Car stopped"); } } class Bike implements Vehicle { public void start() { System.out.println("Bike started"); } public void stop() { System.out.println("Bike stopped"); } }
Abstract Class Interface
Can have abstract and concrete methods All methods are abstract by default (before Java 8)
Can have instance variables Can only have static final variables
Supports single inheritance Supports multiple inheritance
Can have constructors Cannot have constructors

Constructors

A constructor is a special method that is automatically called when an object of a class is created. It is used to initialize the object.

Types of Constructors

  • Default Constructor: No parameters
  • Parameterized Constructor: With parameters
  • Copy Constructor: Creates object using another object
// Constructor examples class Student { String name; int age; // Default constructor Student() { name = "Unknown"; age = 0; } // Parameterized constructor Student(String n, int a) { name = n; age = a; } // Copy constructor Student(Student s) { name = s.name; age = s.age; } void display() { System.out.println("Name: " + name + ", Age: " + age); } } // Using constructors Student s1 = new Student(); // Default constructor Student s2 = new Student("John", 20); // Parameterized constructor Student s3 = new Student(s2); // Copy constructor

Constructor Characteristics

  • Same name as the class
  • No return type (not even void)
  • Automatically called when object is created
  • Can be overloaded
  • If no constructor is defined, compiler provides a default constructor

Access Modifiers

Access modifiers control the visibility and accessibility of classes, methods, and variables.

Types of Access Modifiers

Modifier Same Class Same Package Subclass Other Packages
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
// Access modifiers example class AccessExample { private int privateVar; // Accessible only within this class int defaultVar; // Accessible within package protected int protectedVar; // Accessible within package and subclasses public int publicVar; // Accessible everywhere private void privateMethod() { } void defaultMethod() { } protected void protectedMethod() { } public void publicMethod() { } }
Exam Tip: Remember the order of access modifiers from most restrictive to least: private → default → protected → public.

Static Keyword

The static keyword in Java is used for memory management mainly. It can be applied to variables, methods, blocks, and nested classes. The static keyword belongs to the class rather than the object.

Static Variables

  • Also known as class variables
  • Shared among all instances of the class
  • Memory allocated only once when class is loaded

Static Methods

  • Belongs to the class rather than object
  • Can be called without creating an object
  • Can access only static data
  • Cannot use this or super keywords
// Static keyword example class Counter { static int count = 0; // Static variable Counter() { count++; // Increment static variable } static void displayCount() { // Static method System.out.println("Count: " + count); } } // Using static members Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); Counter.displayCount(); // Output: Count: 3
Important: The main() method in Java is static because it needs to be called by JVM without creating an object of the class.

OOP vs Procedural Programming

Understanding the differences between Object-Oriented Programming and Procedural Programming is crucial.

Aspect Procedural Programming Object-Oriented Programming
Program Division Divided into functions Divided into objects
Approach Top-down approach Bottom-up approach
Data Security Less secure More secure (encapsulation)
Code Reusability Limited reusability High reusability (inheritance)
Data Access Data can move freely Data is encapsulated in objects
Overloading Not supported Supported (polymorphism)
Examples C, Pascal, FORTRAN Java, C++, Python

Benefits of Object-Oriented Programming

OOP offers numerous advantages over other programming paradigms.

Main Benefits of OOP

  • Modularity: Code is organized into classes and objects
  • Reusability: Inheritance allows code reuse
  • Maintainability: Easy to maintain and modify
  • Scalability: Easy to extend and scale applications
  • Security: Data hiding through encapsulation
  • Flexibility: Polymorphism provides flexibility
  • Problem Solving: Better modeling of real-world problems
  • Collaboration: Multiple developers can work on different classes

Real-world Applications of OOP

  • Banking Systems: Account, Customer, Transaction classes
  • E-commerce: Product, ShoppingCart, User classes
  • Game Development: Player, Enemy, Weapon classes
  • GUI Applications: Button, Window, Menu classes
  • Database Systems: Table, Record, Query classes
Exam Tip: Be prepared to explain the benefits of OOP with real-world examples. This is a common question in competitive exams.