Concept Flow - OOP principles overview
Start
Encapsulation
Inheritance
Polymorphism
Abstraction
End
This flow shows the four main OOP principles in order: Encapsulation, Inheritance, Polymorphism, and Abstraction.
Jump into concepts and practice - no test required
class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
| Step | Action | Object Type | Method Called | Output |
|---|---|---|---|---|
| 1 | Create Dog object assigned to Animal reference | Dog | none | none |
| 2 | Call sound() on Animal reference | Dog | sound() | Bark |
| 3 | End of main method | none | none | none |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| a | null | Dog object reference | Dog object reference | Dog object reference |
OOP Principles in Java: - Encapsulation: Hide data inside classes - Inheritance: Child classes reuse parent code - Polymorphism: Same method acts differently - Abstraction: Show only needed details Use classes and methods to organize code clearly.
extends to inherit from a parent class.implements is for interfaces, super accesses parent members, and inherits is not a Java keyword.class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}a is declared as Animal but refers to a Dog instance. The sound() method is overridden in Dog.sound() method runs, printing "Bark".class Vehicle {
private int speed;
public int getSpeed() { return speed; }
}
class Car extends Vehicle {
public void setSpeed(int speed) { this.speed = speed; }
}speed is private in Vehicle, so Car cannot access it directly.setSpeed tries to assign this.speed, which is not accessible, causing a compile error.double getArea() in a base class or interface and having each shape provide its own implementation?getArea(), meaning the method behaves differently depending on the object.