1. Encapsulation
Encapsulation protects the internal state of an object by restricting direct access using private fields. Access is provided through getter and setter methods.
public class Person {
private String name; // hidden data
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
public static void main(String[] args) {
Person p = new Person();
p.setName("John");
p.setAge(25);
System.out.println(p.getName());
System.out.println(p.getAge());
}
} 2. Inheritance
Inheritance allows one class (child) to acquire fields and methods from another class (parent). This promotes code reuse and method overriding.
class Vehicle {
protected String brand = "Honda";
public void start() {
System.out.println("Vehicle is starting...");
}
}
class Car extends Vehicle {
public void drive() {
System.out.println("Car is driving...");
}
public static void main(String[] args) {
Car c = new Car();
c.start();
c.drive();
System.out.println(c.brand);
}
} 3. Polymorphism
Polymorphism allows the same method to behave differently depending on the object that invokes it.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
public void sound() {
System.out.println("Cat says: Meow");
}
}
class Dog extends Animal {
public void sound() {
System.out.println("Dog says: Woof");
}
}
public class TestPoly {
public static void main(String[] args) {
Animal a1 = new Cat();
Animal a2 = new Dog();
a1.sound(); // Cat version
a2.sound(); // Dog version
}
} 4. Abstraction
Abstraction hides implementation details and exposes only essential functionality. Achieved using abstract classes and interfaces.
A. Abstract Class
abstract class Shape {
abstract double area();
public void display() {
System.out.println("This is a shape");
}
}
class Circle extends Shape {
double radius = 5;
double area() {
return 3.14 * radius * radius;
}
public static void main(String[] args) {
Circle c = new Circle();
c.display();
System.out.println("Area = " + c.area());
}
} B. Interface
interface Animal {
void sound();
void sleep();
}
class Lion implements Animal {
public void sound() {
System.out.println("Lion roars");
}
public void sleep() {
System.out.println("Lion sleeps");
}
public static void main(String[] args) {
Lion l = new Lion();
l.sound();
l.sleep();
}
} Best Practices of OOP in Java
- Use encapsulation to protect internal data.
- Apply inheritance only when classes share real relationships.
- Use polymorphism to simplify conditional logic.
- Prefer interfaces when defining behavior without implementation.
- Keep classes focused on a single responsibility.