OOP Principles
Master the 4 pillars of OOP: Inheritance, Polymorphism, Encapsulation, and Abstraction.
Master the 4 pillars of OOP: Inheritance, Polymorphism, Encapsulation, and Abstraction. This hands-on tutorial focuses on practical implementation of oop principles concepts.
OOP Principles
Object-Oriented Programming (OOP) is built on four main pillars.
1. Encapsulation
Bundling data (variables) and methods together and restricting access to the inner workings of that object.
- Use
privatevariables. - Use
publicGetters and Setters to access them.
class Person {
private String name; // Restricted access
// Getter
public String getName() { return name; }
// Setter
public void setName(String newName) { this.name = newName; }
}
2. Inheritance
A mechanism where one class acquires the properties and behaviors of a parent class.
- Keyword:
extends. - Parent Class (Superclass) vs Child Class (Subclass).
class Vehicle {
void honk() { System.out.println("Beep!"); }
}
class Car extends Vehicle {
// Car inherits honk()
}
3. Polymorphism
"Many forms". It allows us to perform a single action in different ways.
- Method Overloading: Compile-time polymorphism (Same name, diff params).
- Method Overriding: Runtime polymorphism (Redefining separate method in subclass).
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Pig extends Animal {
void sound() { System.out.println("Oink"); } // Overriding
}
4. Abstraction
Hiding internal details and showing only functionality.
- Abstract Class: Cannot be instantiated. Can have abstract (empty) and regular methods.
- Interface: A completely "abstract class" (pre-Java 8).
Interactive Code
See Inheritance in action!
AI Mentor
Confused about "Java OOP pillars: Inheritance, Encapsulation, Polymorphism, Abstraction"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3Which keyword is used to inherit a class?
Next Steps
Let's look at some advanced OOP concepts like Interfaces and Abstract Classes in more detail.