Deep Core of OOPs in Java
1. Class and Object
A class is a blueprint for objects. It defines properties and behaviors.
An object is an instance of a class.
Example:
class Car {
String brand;
void drive() {
System.out.println("Driving...");
Car car = new Car();
car.drive();
2. Inheritance (IS-A Relationship)
Inheritance allows one class to acquire the properties of another class.
Example:
class Animal {
void eat() { System.out.println("Eating..."); }
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
Dog d = new Dog();
d.eat();
d.bark();
Deep Core of OOPs in Java
3. Polymorphism (Compile-time and Runtime)
Polymorphism means the ability to take many forms.
- Compile-time (Method Overloading):
class MathUtil {
int sum(int a, int b) { return a + b; }
int sum(int a, int b, int c) { return a + b + c; }
- Runtime (Method Overriding):
class Animal {
void sound() { System.out.println("Animal sound"); }
class Cat extends Animal {
void sound() { System.out.println("Meow"); }
Animal a = new Cat();
a.sound(); // Meow
4. Encapsulation (Data Hiding)
Encapsulation is the process of wrapping data and code into a single unit.
Example:
class Account {
private int balance;
public int getBalance() { return balance; }
public void setBalance(int amount) { balance = amount; }
}
Deep Core of OOPs in Java
5. Abstraction (Hiding Implementation)
Abstraction hides internal details and shows only necessary parts.
Example using abstract class:
abstract class Shape {
abstract void draw();
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); }
Example using interface:
interface Vehicle {
void start();
class Bike implements Vehicle {
public void start() { System.out.println("Bike starting"); }
6. Association, Aggregation, Composition
- Association: General connection between classes.
- Aggregation: HAS-A relationship where child can exist independently.
- Composition: Strong HAS-A where child can't exist without parent.
Example of Composition:
class Engine {
void start() { System.out.println("Engine starting..."); }
}
Deep Core of OOPs in Java
class Car {
private final Engine engine = new Engine();
void startCar() { engine.start(); }
7. SOLID Principles (OOP Best Practices)
- S: Single Responsibility Principle
- O: Open/Closed Principle
- L: Liskov Substitution Principle
- I: Interface Segregation Principle
- D: Dependency Inversion Principle
These principles improve maintainability, testability, and scalability.