OOP stands for object-oriented programming. It is a programming paradigm that revolves around the object rather than function and procedure. In other words, it is an approach for developing applications that emphasize objects. An object is a real-world entity that contains data and code. It allows binding data and code together.
Here, objects mean real-world entities like cars, bikes, ATMs, etc.
Procedural Programming | OOPS |
programs are divided into parts called functions | Programs are divided into objects |
Overloading is not possible | Overloading is possible |
Inheritance is not possible | Inheritance is possible |
Data hiding is not present | Data hiding is present |
It follows a top-down approach | It follows a bottom-up approach |
It focuses on the process. | It focuses on data. |
Ex:- C, Pascal etc. | Ex:- Java, C++, Python etc. |
OOP Concepts in Java
Java follows Object-Oriented Programming (OOP), which is based on the following nine key concepts:
Class – A blueprint for creating objects.
Object – An instance of a class with state and behavior.
Encapsulation – Hiding internal details and exposing only the necessary parts.
Polymorphism – The ability to take multiple forms (method overloading & overriding).
Inheritance – Acquiring properties and behaviors from a parent class.
Abstraction – Hiding implementation details and showing only essential features.
Association – A relationship between two classes without ownership.
Composition – A strong association where one class owns another.
The Four Pillars of OOP
These are the core principles of OOP in Java:
Encapsulation
Inheritance
Polymorphism
Abstraction
Note: Concepts and pillars are different. Java has 8 main concepts, but only 4 pillars of OOP.
Benefits of OOP in Java
Reusability – Write once, and use multiple times to reduce redundancy.
Data Redundancy – Avoids duplication by using shared class definitions.
Code Maintenance – Easier to update and manage code efficiently.
Security – Encapsulation and abstraction restrict unnecessary data access.
Easy Troubleshooting – Objects simplify debugging and modification.
Better Design – Stable base classes reduce errors in derived classes.
Classes in Java
A class in Java is a blueprint or template of an object from which an object is created. It doesn’t take up space in memory. It is a user-defined data type. Inside a class, we define variables, constants, and functions. It is an example of data binding. It is a logical entity.
Syntax
class ClassName {
// Fields (variables)
// Constructors
// Methods
}
Objects in Java
An Object is a real-world entity that has attributes, behavior, and properties. It is referred to as an instance of the class. It contains member functions and variables that we have defined in the class. It occupies space in the memory. Different objects have different states or attributes and behaviors.
Object is a real-world entity, every object has a state, and the behavior state tells us how the object looks, and the behavior tells us what the object does.
Syntax
ClassName objectName = new ClassName();
Difference B/W Classes and Objects in Java
Class | Object |
It is a logical entity | It is a real-world entity |
It is based on concepts. | It is based on the real world |
It uses the keyword class when declared. | It uses the new keyword to create an object. |
It does not occupy space in the memory. | It occupies space in the memory. |
It is a data type that represents the blueprint of an object. | It is an instance of the class. |
Here, Car is a class, and the Audi and BMW are instances of that Car class. So all the properties and behavior of the Car class are also present in its instance.
Let’s take a look at the Car class below and how to create instances of the Car class called Audi and
BMW:
class Car {
// state
private String color;
private String type;
private String brand;
private int speed;
// Constructor
public Car(String color, String type, String brand) {
this.color = color;
this.type = type;
this.brand = brand;
this.speed = 0; // Initial speed
}
//behavior
// Method to increase speed
public void increaseSpeed(int increment) {
speed += increment;
System.out.println(brand + " speed increased to " + speed + " km/h");
}
// Method to apply brake
public void applyBrake(int decrement) {
speed -= decrement;
if (speed < 0) speed = 0;
System.out.println(brand + " speed reduced to " + speed + " km/h");
}
// Method to drive
public void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}
// Method to display car details
public void displayDetails() {
System.out.println("Brand: " + brand + ", Type: " + type + ", Color: " + color);
}
public static void main(String[] args) {
Car audi = new Car("Red", "Sedan", "Audi");
Car bmw = new Car("Blue", "SUV", "BMW");
audi.displayDetails();
audi.increaseSpeed(50);
audi.drive();
audi.applyBrake(20);
System.out.println();
bmw.displayDetails();
bmw.increaseSpeed(60);
bmw.drive();
bmw.applyBrake(30);
}
}
Output
Brand: Audi, Type: Sedan, Color: Red
Audi speed increased to 50 km/h
Audi is driving at 50 km/h
Audi speed reduced to 30 km/h
Brand: BMW, Type: SUV, Color: Blue
BMW speed increased to 60 km/h
BMW is driving at 60 km/h
BMW speed reduced to 30 km/h
Encapsulation in Java
The process of wrapping the data and code, which is acting on the data together, into a single unit, is called Encapsulation. we can achieve encapsulation by creating the variables of class as private and creating the getter and setter method as public to view and modify the variables. it is also known as data hiding.
Advantages
Loosely coupled code.
Better access control & security.
package oops;
public class Encapsulation {
public static void main(String[] args) {
// creating the object
Student student=new Student();
// setting the value of the variables
student.setAge(10);
student.setName("Ayush");
// Accessing the value of the variables
System.out.println(student.getName());
System.out.println(student.getAge());
}
}
class Student{
// variables as private
private String name;
private int age;
// getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Output
Ayush
10
In this example, we are creating the variables of the class as private so other classes can’t access them. This concept is called encapsulation, and we provide the getter and method to modify and view the value of the variables.
It provides you with control over the data. Suppose you want to set the value of age to be greater than 18 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.
Abstraction in Java
The Process of hiding the internal implementation and showing only essential functionality to the user is known as abstraction. It is also known as detail hiding. In Java, it is achieved through interface and abstract classes.
Let’s explore an example, when we are driving a car, if we want to stop the car, then we just apply the break and the car speed will reduce, we don’t know how the car speed is reduce and also there is no need to know as a driver how the things works in car.
So we can say that brakes and other functionalities of the car are abstracted from us. Similarly, in the cellphone, how the call is made is abstracted to us:
package oops;
public interface Car {
void applyBreak();
void start();
}
class BMW implements Car{
public void applyBreak(){
System.out.println("Applying break");
}
public void start(){
System.out.println("Starting the car");
}
}
In this example, Car is an interface, and applyBreak()
and start()
are methods of the Car interface, and the class BMW implements the Car interface, so the user only knows about the abstraction methods that are applyBreak() start()
but doesn’t know about the internal implementations. In this example, what we do just hides the internal details of the class.
You can learn more about the interface and abstract classes in the next article.
Polymorphism in Java
Polymorphism is a combination of two words: poly means “Many” and morphism means “Form”. Means that the same entity (method) having different behavior is called polymorphism.
Example:
A person can be a father, boy, teacher or can be a dancer, writer, programmer as well.
Water is a liquid, solid, or gas.
Types of polymorphism.
Compile Time / static polymorphism
Run Time/ Dynamic polymorphism
Compile Time Polymorphism
A polymorphism that is achieved at compile time is known as compile time polymorphism. Method Overloading is an example of compile time polymorphism.
Runtime polymorphism
A polymorphism that is achieved at run time is known as run time polymorphism. Method Overriding is an example of runtime polymorphism.
Method Overloading in Java
Two methods are said to be overloaded if they have the same name but variations in parameters. variation in parameter means. In method overloading, the method signature is different.
Number of parameters
Position of parameters
Data type of the parameters
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers (overloaded)
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double numbers (overloaded)
double add(double a, double b) {
return a + b;
}
}
public class MethodOverloadingExample {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum1 = calculator.add(5, 10); // Calls the first method
int sum2 = calculator.add(5, 10, 15); // Calls the second method
double sum3 = calculator.add(2.5, 3.5); // Calls the third method
System.out.println("Sum1: " + sum1);
System.out.println("Sum2: " + sum2);
System.out.println("Sum3: " + sum3);
}
}
Here in this example, we have a Calculator
class with overloaded add
methods. The methods have the same name but different parameter lists (number and type of parameters). Depending on the number and types of arguments passed, the appropriate overloaded method is called.
Method Overriding in Java
If the child class method is not satisfied with its parent class method implementation, then the child can override that implementation. This concept is called method overriding.
Method Overriding is only possible through inheritance. At runtime, the decision is made on whether to call the method from the parent class or the child class, depending on the object's actual type.
Additionally, in method overriding, the method signature is the same.
class Vehicle {
void start() {
System.out.println("The vehicle starts");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("The car starts with a key ignition");
}
}
class Bike extends Vehicle {
@Override
void start() {
System.out.println("The bike starts with a kick");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Vehicle();
myVehicle.start(); // Calls the start method in Vehicle
Vehicle myCar = new Car();
myCar.start(); // Calls the overridden start method in Car
Vehicle myBike = new Bike();
myBike.start(); // Calls the overridden start method in Bike
}
}
In this example, Vehicle
is a class having methods as start
while Bike
and Car
is the subclass of the Vehicle
class where we override the start()
method according to the use case. The specific implementation is executed depending on the type of object at runtime.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse the methods and fields of the parent class. Moreover, you can add new methods and fields to your current class.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Parent / super class - A class in which properties and behaviors are acquired by the child class.
Child/subclass -A class that inherits properties and behaviors from the superclass.
Types of Inheritance
Single level Inheritance
Hierarchical Inheritance
Multiple Inheritance (In Java, through the class is not possible)
Hybrid Inheritance (in Java, through class is not possible)
Multilevel Inheritance
Single Inheritance
A single-child class acquires the properties and behaviors of the superclass. In a single level of inheritance, there is only one sub and one superclass. It inherits the properties and behavior of a single-parent class. When a class inherits another class, it is known as a single inheritance.
Multilevel Inheritance
Acquiring the properties and behaviors from another derived class. Multiple-level inheritance allows a subclass to inherit from a superclass that already inherits from another superclass. To put it another way, a subclass can inherit from a parent class that is a child class of another parent class.
Hierarchical Inheritance
Two child classes are inheriting the properties and behavior from a single super/ parent class. or we can say that when two or more classes inherit a single class, it is known as hierarchical inheritance. In the example given below, the B and C classes inherit the A class, so there is hierarchical inheritance.
Multiple Inheritance
When one class inherits multiple classes, then this is known as multiple inheritance. In Java, this is not possible through the class because of ambiguity or the diamond problem, but with the help of an interface, we can achieve.
Hybrid Inheritance
It is a combination of two or more than two inheritances. In Java, this is not possible through the class, but with the help of an interface, we can achieve it.
Conclusion
Object-oriented programming (OOP) is a powerful approach to designing and organizing code that makes applications easier to build, manage, and scale. Through OOP concepts, developers create efficient, reusable, and maintainable code structures.
OOP is built on four fundamental pillars that govern how objects interact and function in a program:
Encapsulation – Protects data by keeping it private within a class and exposing only what's necessary.
Abstraction – Simplifies complex implementations by providing a clean interface for users.
Inheritance – Enables classes to inherit properties and behaviors from other classes, promoting code reuse.
Polymorphism – Allows a single action to behave differently in various contexts, enhancing code flexibility.
These concepts are essential for writing clean, structured code. For a deeper understanding, explore our dedicated articles on each pillar. Mastering OOP principles will improve your programming skills and help you tackle real-world problems more effectively.