What is OOP in java

0

What is Object-Oriented Programming (OOP) in Java?

Object-Oriented Programming, commonly known as OOP, is one of the most important programming paradigms used in Java. Almost every Java application, from small desktop software to enterprise banking systems and large cloud-based applications, is built using object-oriented principles.

When students first begin learning Java, one of the biggest questions they ask is, "Why does Java focus so much on classes and objects?" The answer lies in how modern software is developed. As software grows in size, writing everything inside functions becomes difficult to manage. OOP provides a structured way to organize code so that it becomes easier to understand, maintain, test, and extend.

Rather than thinking only in terms of functions and procedures, Object-Oriented Programming encourages developers to think in terms of real-world entities. Each entity contains its own data and behavior, making software much closer to the way humans naturally understand the world.


What is Object-Oriented Programming?

Object-Oriented Programming is a programming approach where software is designed using objects. An object represents a real or conceptual entity that contains both information (called data or state) and actions (called behavior).

Instead of creating one long program containing hundreds or thousands of lines of code, developers divide the application into multiple independent objects. Each object performs a specific responsibility and interacts with other objects whenever required.

For example, consider an online shopping application. Instead of writing one huge program, developers create different objects such as Customer, Product, Order, Payment, ShoppingCart, Delivery, and Invoice. Each object manages its own information and responsibilities.

A useful way to think about OOP is that every object knows how to manage itself. Instead of one part of the program controlling everything, responsibilities are distributed among different objects.


Why Was Object-Oriented Programming Introduced?

Before Object-Oriented Programming became popular, many applications were developed using procedural programming. Procedural programming works well for smaller applications, but as software grows, several challenges begin to appear.

Developers often experience problems such as duplicated code, difficult maintenance, poor scalability, and increased chances of introducing bugs while modifying existing functionality.

As software projects became larger, companies needed a better way to organize code. This need eventually led to the widespread adoption of Object-Oriented Programming.

Problems with Large Procedural Programs

  • Code becomes difficult to understand.
  • Changes in one area may affect unrelated parts.
  • Reusing code becomes difficult.
  • Testing individual components is harder.
  • Team collaboration becomes less efficient.
  • Maintaining large projects becomes expensive.

Object-Oriented Programming addresses these issues by organizing software into reusable and independent components called objects.


Why Do Developers Prefer OOP?

Most real-world software today is continuously evolving. New features are added every month, security patches are released regularly, and customer requirements change frequently. OOP makes these continuous improvements easier because different parts of the software remain organized into separate components.

For example, suppose an e-commerce company wants to introduce a new payment method. If the payment logic is properly organized inside a Payment object, developers can update that part without affecting products, orders, or customers.

This modular approach significantly reduces development time and improves software quality.


Understanding OOP Through a Real-World Example

Consider a car. Every car has certain characteristics and performs certain actions.

Real-World Car Object-Oriented Concept
Color Data (State)
Brand Data (State)
Speed Data (State)
Start Engine Behavior (Method)
Stop Engine Behavior (Method)
Accelerate Behavior (Method)

Similarly, in Java, an object stores its own data and provides methods to perform operations on that data.


Objects Exist Everywhere

One mistake I frequently notice among beginners is assuming that objects only exist in programming. In reality, object-oriented programming simply models the world around us.

Object State Behavior
Student Name, Roll Number, Marks Study(), AttendClass(), GiveExam()
Bank Account Balance, Account Number Deposit(), Withdraw(), Transfer()
Employee Name, Salary, Department Work(), Login(), Logout()
Mobile Phone Brand, Battery, Storage Call(), Charge(), InstallApp()

The primary goal of OOP is to represent such entities inside software as objects that interact with each other.


The Four Main Pillars of OOP

Java's Object-Oriented Programming model is built upon four core principles. These principles make applications flexible, reusable, and easier to maintain.

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

These concepts will be studied in detail later in the roadmap. At this stage, it is enough to know that together they form the foundation of object-oriented software design.

Many beginners try to memorize these four pillars without understanding why they exist. Focus first on understanding objects and classes. The advanced principles become much easier once you start building real programs.


Procedural Programming vs Object-Oriented Programming

Procedural Programming Object-Oriented Programming
Focuses on functions Focuses on objects
Data is often shared globally Data stays inside objects
Less reusable Highly reusable
Difficult for large applications Suitable for enterprise software
Harder to maintain Easier to maintain
Limited scalability Excellent scalability

Your First Object-Oriented Java Example

class Student {

    String name;
    int age;

    void study() {
        System.out.println(name + " is studying.");
    }
}

public class Main {

    public static void main(String[] args) {

        Student s1 = new Student();

        s1.name = "Rahul";
        s1.age = 20;

        s1.study();
    }
}

Although you have not yet learned classes and objects in detail, this example demonstrates the basic idea of OOP. A Student object stores information such as name and age, and it also provides behavior through the study() method.


Classes and Objects: The Foundation of OOP

Before you can master Object-Oriented Programming, you need to clearly understand the relationship between a class and an object. Nearly every Java program you write will begin with these two concepts.

Many students initially assume that a class and an object are the same thing. They are closely related, but they are not identical. A class serves as a blueprint or template, while an object is the actual entity created from that blueprint.


What is a Class?

A class is a user-defined blueprint that describes what an object should contain. It defines the properties (data) and behaviors (methods) that every object created from it will have.

Think of a class as an architectural drawing of a house. The drawing specifies the number of rooms, doors, windows, and other details, but you cannot live inside the drawing itself. Similarly, a Java class only defines the structure—it does not represent a real object until an instance is created.

A class consumes very little memory because it simply contains the definition of an object. Memory for data is allocated only when objects are created.


What is an Object?

An object is a real instance of a class. It occupies memory, stores actual values, and can execute the methods defined in its class.

Unlike a class, which is only a template, an object represents something that actually exists while the program is running.

Class Object
Blueprint Real instance
Defines structure Stores actual values
No real data Contains real data
Declared once Can create many objects
No separate memory for variables Memory allocated in Heap

Understanding with a Real Example

Suppose a company manufactures laptops. Every laptop shares common characteristics such as brand, RAM, processor, and storage. Instead of describing every laptop individually, engineers first create a design specification.

In Java:

  • Laptop specification → Class
  • Individual laptop → Object

Thousands of laptops can be manufactured using the same design. Likewise, thousands of Java objects can be created from one class.


Creating Your First Class

class Car {

    String brand;
    String color;

    void start() {
        System.out.println("Car Started");
    }

}

This class only describes what every Car object should contain. No memory is allocated for brand or color until an object is created.


Creating an Object

public class Main {

    public static void main(String[] args) {

        Car car1 = new Car();

        car1.brand = "Toyota";
        car1.color = "White";

        car1.start();

    }

}

Here, new Car() creates a new object. The variable car1 stores a reference to that object.


Creating Multiple Objects

One of the biggest advantages of OOP is that one class can create many independent objects.

class Student {

    String name;
    int age;

    void display() {

        System.out.println(name + " : " + age);

    }

}

public class Main {

    public static void main(String[] args) {

        Student s1 = new Student();
        Student s2 = new Student();
        Student s3 = new Student();

        s1.name = "Amit";
        s1.age = 20;

        s2.name = "Neha";
        s2.age = 19;

        s3.name = "Riya";
        s3.age = 21;

        s1.display();
        s2.display();
        s3.display();

    }

}

Although all three objects belong to the same class, each stores its own data independently. Changing one object does not affect the others.


How Java Creates an Object Internally

When Java executes the following statement:

Student s1 = new Student();

Several steps occur behind the scenes:

  • Java checks the Student class definition.
  • Memory is allocated in the Heap.
  • All instance variables receive default values.
  • The object's constructor is executed.
  • A reference to the object is returned.
  • The reference is stored in variable s1.

Many beginners believe that s1 stores the actual object. It does not. It only stores the reference (address) of the object stored in Heap memory.


Where Are Objects Stored?

Memory Area Stores
Stack Memory References and local variables
Heap Memory Objects and instance variables
Method Area Class information and bytecode

You will study Java memory management in much greater detail later in the roadmap. For now, remember that objects live in the Heap, while reference variables generally reside in the Stack.


Why Is This Design Useful?

Separating blueprints from real objects makes software highly reusable. Instead of writing separate code for every employee, customer, or product, developers define one class and create as many objects as needed.

This design keeps programs cleaner, reduces duplication, and makes future enhancements much easier.


Real-World Usage of Classes and Objects

Application Possible Classes
Online Shopping Customer, Product, Order, Cart
Banking System Account, Customer, Loan, Transaction
Hospital Doctor, Patient, Appointment
School Management Student, Teacher, Course
Food Delivery Restaurant, Menu, Order, DeliveryBoy

If you later work with frameworks such as Spring Boot, you'll notice that almost every service, controller, entity, and repository is implemented as a class. Understanding classes and objects thoroughly now will make learning advanced Java much easier.


Characteristics of an Object

Every object in Java is defined by three fundamental characteristics. Understanding these characteristics helps you recognize why objects are considered the building blocks of Object-Oriented Programming. Whether you create a simple Student object or a complex Banking System, every object possesses these three properties.

Characteristic Description
State The current data or values stored inside the object.
Behavior The operations or actions the object can perform.
Identity A unique identity that distinguishes one object from another.

State

The state of an object represents its current information. In Java, this information is usually stored in instance variables.

class Employee {

    String name;
    double salary;
    String department;

}

Here, name, salary, and department together describe the current state of an Employee object.


Behavior

Behavior defines what an object can do. In Java, behaviors are implemented using methods.

class Employee {

    void work() {
        System.out.println("Employee is working.");
    }

    void attendMeeting() {
        System.out.println("Employee joined the meeting.");
    }

}

Methods allow objects to perform meaningful actions. Without methods, objects would merely store information without being able to interact with the rest of the application.


Identity

Even if two objects contain identical values, Java still treats them as separate objects. Each object occupies its own memory location and therefore has its own identity.

Student s1 = new Student();
Student s2 = new Student();

Although both objects belong to the same class, they are completely independent. Modifying one object does not automatically change the other.

Identity becomes especially important when working with collections, databases, and enterprise applications where thousands of objects may exist simultaneously.


Advantages of Object-Oriented Programming

Object-Oriented Programming became popular because it solves many of the challenges faced by large software projects. Most modern Java applications rely heavily on these advantages.

1. Code Reusability

Developers can reuse existing classes instead of rewriting similar code repeatedly. This reduces development time and improves consistency across projects.

2. Better Code Organization

Instead of placing all functionality inside one file, OOP divides software into logical classes. Each class is responsible for a specific task, making projects easier to understand.

3. Easier Maintenance

Real-world applications continue evolving for years. When code is properly organized into classes, adding new features or fixing bugs becomes much simpler.

4. Improved Collaboration

Large software projects often involve dozens or even hundreds of developers. Since each class has a well-defined responsibility, multiple developers can work on different modules simultaneously without interfering with each other's work.

5. Better Security

OOP encourages keeping data inside objects and exposing only the necessary operations. This helps prevent accidental modification of important information.

6. Scalability

As applications grow, new classes can be introduced without rewriting the entire system. This flexibility makes OOP ideal for enterprise software.


Where is OOP Used?

Sometimes beginners assume OOP is only useful for academic projects. In reality, nearly every professional Java application uses object-oriented principles extensively.

Industry How OOP is Used
Banking Accounts, Customers, Transactions, Loans
E-Commerce Products, Orders, Payments, Shopping Carts
Healthcare Patients, Doctors, Appointments, Reports
Education Students, Teachers, Courses, Exams
Social Media Users, Posts, Comments, Messages
Travel Booking Flights, Hotels, Tickets, Reservations

Whether you're building a REST API with Spring Boot, developing Android applications, or creating desktop software, you'll be designing classes and working with objects throughout your project.


How OOP Helps in Enterprise Development

During real-world development, software rarely consists of a single program. Enterprise applications may contain thousands of classes spread across hundreds of packages.

For example, in an online banking application, separate classes may be responsible for:

  • Customer Management
  • Authentication
  • Transaction Processing
  • Loan Services
  • Notifications
  • Fraud Detection

Because each module is represented by classes and objects, developers can improve one feature without affecting unrelated modules.


Common Beginner Mistakes

Learning OOP is not difficult, but beginners often develop misconceptions that can slow their progress. Being aware of these mistakes early can save a great deal of time.

  • Thinking a class is an object.
  • Believing every variable is an object.
  • Ignoring the purpose of methods.
  • Creating unnecessary classes for everything.
  • Trying to memorize definitions without writing programs.
  • Assuming OOP is only about classes and objects while ignoring the four pillars.

Best Practices While Learning OOP

Developing strong object-oriented thinking takes practice. Focus on designing small applications before attempting large projects.

  • Model real-world entities as classes.
  • Keep each class responsible for one primary task.
  • Choose meaningful class and method names.
  • Write multiple object examples instead of only one.
  • Practice by designing simple systems such as a library, bank, or school management application.
  • Understand concepts instead of memorizing definitions.

Interview Insight

Questions related to Object-Oriented Programming are among the most frequently asked in Java interviews. Interviewers often expect candidates to explain OOP in their own words rather than reciting textbook definitions.

Common Interview Question Expected Focus
What is OOP? Definition with practical understanding.
Why is Java called object-oriented? Everything revolves around classes and objects.
Difference between Class and Object? Blueprint vs Instance.
What are the four pillars of OOP? Encapsulation, Inheritance, Polymorphism, Abstraction.
Why is OOP preferred? Maintainability, Reusability, Scalability.

Practice Exercises

The best way to understand Object-Oriented Programming is by writing programs. Reading theory provides a strong foundation, but real understanding develops when you design classes and create objects yourself. Try the following exercises without looking at previous examples.

Exercise 1

Create a Book class with the following properties:

  • Title
  • Author
  • Price

Also create a method named displayBook() that prints all the information about the book.


Exercise 2

Create a MobilePhone class with properties such as brand, model, battery percentage, and storage capacity. Add methods like:

  • call()
  • charge()
  • showDetails()

Exercise 3

Design a simple Banking System by creating an Account class containing:

  • Account Number
  • Account Holder Name
  • Balance

Add methods for depositing money, withdrawing money, and displaying account information.


Exercise 4

Create five Student objects using a single Student class. Store different names and marks for each student and display their information.


Mini Quiz

Answer these questions without referring back to the lesson. If you can answer most of them confidently, you've developed a solid understanding of the basics of Object-Oriented Programming.

No. Question
1 What is Object-Oriented Programming?
2 What is the difference between a class and an object?
3 Can one class create multiple objects?
4 Where are Java objects stored in memory?
5 What are the three characteristics of an object?
6 Why is OOP preferred for large software projects?
7 Name the four pillars of Object-Oriented Programming.
8 What does the new keyword do in Java?
9 Can two objects of the same class store different data?
10 Give one real-world example that can be modeled as an object.

Key Takeaways

  • Object-Oriented Programming organizes software using objects instead of only functions.
  • A class is a blueprint, while an object is an actual instance created from that blueprint.
  • Every object has state, behavior, and identity.
  • One class can create any number of independent objects.
  • Objects store their own data and perform operations through methods.
  • Java applications rely heavily on Object-Oriented Programming because it improves maintainability and scalability.
  • OOP is widely used in enterprise software, web applications, Android apps, cloud services, and backend systems.
  • Understanding classes and objects is essential before learning advanced OOP concepts such as Encapsulation, Inheritance, Polymorphism, and Abstraction.

Frequently Asked Questions (FAQs)

Is Java a purely Object-Oriented Programming language?

No. Java is primarily an object-oriented language, but it also supports primitive data types such as int, char, boolean, and others that are not objects. Because of this, Java is often described as an object-oriented language rather than a purely object-oriented one.


Why should beginners learn OOP before advanced Java topics?

Most advanced Java concepts—including collections, exception handling, multithreading, file handling, JDBC, Spring Boot, and Hibernate—are built around classes and objects. A solid understanding of OOP makes these topics much easier to learn.


Can a Java program run without creating objects?

Although Java uses classes extensively, many practical programs require objects to perform meaningful work. Even the JVM starts execution by calling the main() method of a class. As applications grow, object creation becomes an essential part of software design.


Is OOP only useful for Java?

No. Object-Oriented Programming is a programming paradigm used by many languages, including C++, C#, Python, Kotlin, Swift, and PHP. Once you understand OOP in Java, the same principles can be applied in many other programming languages.


What should I learn after Object-Oriented Programming?

The next step is to understand how classes and objects are created in detail. You'll then learn constructors, the this keyword, static members, packages, access modifiers, and finally the four pillars of OOP that make Java applications powerful and maintainable.


Object-Oriented Programming is much more than a programming technique—it is a way of thinking about software design. By modeling real-world entities as classes and creating objects that manage their own data and behavior, developers can build applications that are organized, reusable, scalable, and easier to maintain. As you continue your Java journey, you'll discover that nearly every major feature of the language builds upon the concepts introduced in this lesson. A strong understanding of OOP today will make learning constructors, inheritance, polymorphism, abstraction, frameworks like Spring Boot, and enterprise application development significantly easier in the chapters ahead.

Post a Comment

0Comments
Post a Comment (0)