Java OOP (Object-Oriented Programming) Introduction
What is OOP?
OOP = Object-Oriented Programming
A programming approach based on classes and objects
Used to model real-world entities
Class
A blueprint/template to create objects
Contains:
Variables (data)
Methods (functions)
class Car {
String color;
int speed;
void drive() {
System.out.println("Car is running");
}
}Object
An instance of a class
Used to access class properties and methods
Car c1 = new Car();
c1.color = "Red";
c1.drive();Pillars of OOP
1. Encapsulation š
Wrapping data + methods into a single unit
Use private variables + getters/setters
Data hiding
Secure code
class Student {
private int marks;
public void setMarks(int m) {
marks = m;
}
public int getMarks() {
return marks;
}
}2. Inheritance
One class inherits another class
Use
extendskeyword
Code reuse
Parent ā Child relationship
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}3. Polymorphism
One method, multiple forms
Types:
Method Overloading (compile-time)
Method Overriding (runtime)
class MathUtil {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}4. Abstraction
Hiding implementation details
Show only important features
Key Points:
Use
abstractclass or interfaceReduce complexity
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() {
System.out.println("Start with key");
}
}Advantages of OOP
ā Code reusability
ā Easy maintenance
ā Data security
ā Real-world modeling
Quick Short
Class ā Blueprint
Object ā Instance
Encapsulation ā Data hiding
Inheritance ā Code reuse
Polymorphism ā Many forms
Abstraction ā Hide details