Introduction
We use different ways to organize code. Procedural groups steps one after another. OOP groups data and actions together to model real things.
Jump into concepts and practice - no test required
We use different ways to organize code. Procedural groups steps one after another. OOP groups data and actions together to model real things.
Procedural approach: // Write functions and call them in order OOP approach: // Define classes with data and methods // Create objects from classes // Use objects to perform actions
Procedural code focuses on actions and steps.
OOP code focuses on objects that have both data and actions.
public class ProceduralExample { public static void main(String[] args) { int a = 5; int b = 3; int sum = add(a, b); System.out.println("Sum: " + sum); } public static int add(int x, int y) { return x + y; } }
class Calculator { int a, b; Calculator(int a, int b) { this.a = a; this.b = b; } int add() { return a + b; } } public class OOPExample { public static void main(String[] args) { Calculator calc = new Calculator(5, 3); System.out.println("Sum: " + calc.add()); } }
This program shows both ways to add numbers. Procedural uses a simple function. OOP uses a class with data and method.
public class ProceduralVsOOP { // Procedural method public static int proceduralAdd(int x, int y) { return x + y; } // OOP class static class Adder { int x, y; Adder(int x, int y) { this.x = x; this.y = y; } int add() { return x + y; } } public static void main(String[] args) { // Using procedural approach int result1 = proceduralAdd(10, 20); System.out.println("Procedural sum: " + result1); // Using OOP approach Adder adder = new Adder(10, 20); int result2 = adder.add(); System.out.println("OOP sum: " + result2); } }
Procedural code is easier for small tasks.
OOP helps manage bigger programs by grouping data and actions.
OOP supports concepts like reuse and protection of data.
Procedural approach writes step-by-step instructions.
OOP approach models real things as objects with data and actions.
Choose the approach based on program size and needs.
int speed = 0; speed = speed + 10; System.out.println(speed);
class Dog {
String name;
void bark() {
System.out.println(name + " barks");
}
public static void main(String[] args) {
Dog d = new Dog();
d.bark();
}
}