Learn the core Object-Oriented Programming concepts in Java to build robust, reusable, and modular applications.
Object-Oriented Programming (OOP) in Java is a programming paradigm that focuses on using objects and classes to organize code. It helps developers create modular, reusable, and maintainable software systems.
A class is a blueprint or template for creating objects. It defines the data (fields) and behavior (methods) that the objects will have.
class Car {
String color;
void drive() {
System.out.println("Car is driving");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.color = "Red";
myCar.drive();
}
}
An object is an instance of a class. It represents real-world entities like a car, employee, or student. Each object has its own data and can perform actions defined by its class.
Car car1 = new Car();
Car car2 = new Car();
car1.color = "Blue";
car2.color = "Black";
car1.drive();
car2.drive();
Inheritance allows one class (child) to acquire the properties and methods of another class (parent). It promotes code reusability and hierarchical relationships.
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Bike extends Vehicle {
void wheelie() {
System.out.println("Bike doing a wheelie");
}
}
public class Main {
public static void main(String[] args) {
Bike b = new Bike();
b.start();
b.wheelie();
}
}
Polymorphism means “many forms.” It allows a single function, class, or interface to behave differently based on the context — mainly through method overloading and overriding.
class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Output: Dog barks
}
}
Encapsulation is the process of wrapping data and methods into a single unit (class) and restricting direct access using private fields and public getters/setters.
class Student {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Amit");
System.out.println(s.getName());
}
}
Abstraction hides implementation details and exposes only necessary functionalities. It can be achieved using abstract classes or interfaces in Java.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
}
}
Use classes and objects to model real-world problems. Keep your data encapsulated and maintain data integrity. Reuse code using inheritance and polymorphism. Abstract implementation details to build clean and flexible APIs.