Java - OOP
Java - OOP
java
CopyEdit
public class Car {
// Fields
String color;
int speed;
// Method
void drive() {
System.out.println("The car is driving.");
}
}
2. Object
java
CopyEdit
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Create an object
myCar.color = "Red";
myCar.speed = 100;
myCar.drive(); // Call the method
}
}
3. Encapsulation
4. Inheritance
java
CopyEdit
public class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}
5. Polymorphism
Polymorphism means many forms — the same method name can behave
differently based on the object.
java
CopyEdit
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
b) Method Overloading (Compile-time Polymorphism)
java
CopyEdit
class Math {
int add(int a, int b) {
return a + b;
}
6. Abstraction
a) Abstract Class
java
CopyEdit
abstract class Shape {
abstract void draw();
}
java
CopyEdit
interface Animal {
void sound();
}
🎯 Summary
OOP Concept Description
Class Blueprint for creating objects
Object Instance of a class
Protect data using access
Encapsulation
modifiers
Inheritance Share behavior between classes
One interface, many
Polymorphism
implementations
Hide internal details, show
Abstraction
essentials