Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to Java
Java OOP Concepts Explained

Java OOP Concepts Explained

Java2,199 viewsBy Admin
javaconcepts

The Four Pillars of OOP

Object-Oriented Programming organises code around objects. Java is built on four core principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.

1. Encapsulation

public class Account {
    private double balance;        // hidden
    public double getBalance() { return balance; }
    public void deposit(double n) { if (n > 0) balance += n; }
}

2. Inheritance

class Animal { void eat() { System.out.println("eating"); } }
class Dog extends Animal { void bark() { System.out.println("woof"); } }
// Dog has both eat() and bark()

3. Polymorphism

class Animal { String sound() { return "..."; } }
class Cat extends Animal { String sound() { return "meow"; } }
Animal a = new Cat();
a.sound(); // "meow" — resolved at runtime

4. Abstraction

abstract class Shape { abstract double area(); }
class Circle extends Shape {
    double r;
    double area() { return Math.PI * r * r; }
}

FAQs

Interface vs abstract class?

Use an interface for a contract (multiple inheritance of type); an abstract class for shared base code. More in our Java section.

Why encapsulate fields?

To protect data and control how it's changed through methods.