π What Youβll Learn
- What OOP is and why it's used
- How to create classes and objects
- Concepts like encapsulation, inheritance, and polymorphism
- Real-world analogies to understand OOP better
π§ What is OOP?
Object-Oriented Programming is a style of programming based on the concept of "objects" β like real-world entities.
Java is built entirely around OOP.
Think of a class as a blueprint, and an object as an actual item built from it.
π§° Creating a Class
public class Car {
String color;
int speed;
void drive() {
System.out.println("Driving at " + speed + " km/h");
}
}
This is a blueprint of a Car. It has attributes (color, speed) and a behavior (drive()).
π οΈ Creating Objects
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // create an object
myCar.color = "Red";
myCar.speed = 60;
myCar.drive(); // Output: Driving at 60 km/h
}
}
π§± Encapsulation
Encapsulation = data hiding. Use private variables and public getters/setters:
public class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
𧬠Inheritance
Inheritance = a class can inherit fields and methods from another class.
class Animal {
void speak() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Bark!");
}
}
π Polymorphism
Polymorphism = the same method name can behave differently depending on the object.
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}
Animal myAnimal = new Cat();
myAnimal.sound(); // Output: Meow
π₯ Constructors
Special methods used to initialize objects.
public class Person {
String name;
Person(String n) {
name = n;
}
}
π Example: Simple Class
public class Student {
String name;
int age;
void introduce() {
System.out.println("Hi, I'm " + name);
}
public static void main(String[] args) {
Student s = new Student();
s.name = "Alice";
s.age = 20;
s.introduce(); // Output: Hi, I'm Alice
}
}
π Recap
- OOP helps organize code using objects and classes
- Key concepts: encapsulation, inheritance, polymorphism
- Java is a fully OOP language β master this to build real-world apps