Module 5: Object-Oriented Programming (OOP) Fundamentals
Lesson focusIntroduction to OOP Concepts
A high-level overview of Object-Oriented Programming. Understand the core ideas of objects, classes, and the four main pillars that make OOP a powerful paradigm.
Shifting from Procedural to Object-Oriented: In procedural programming, you write a sequence of steps to perform a task. In Object-Oriented Programming (OOP), you create models of real-world things (or concepts) as objects, which have both data (attributes) and behaviors (methods).
What is a Class? A class is a blueprint or template for creating objects. It defines the properties and methods that all objects of that type will have. For example, you could have a Dog class.
What is an Object? An object is an instance of a class. It is a concrete entity created from the class blueprint, with its own state. For example, you could have three Dog objects: myDog, yourDog, and strayDog, each with its own specific name, age, and breed.
The Four Pillars of OOP:
- 1. Encapsulation: The bundling of data (attributes) and the methods that operate on that data into a single unit (a class). It also involves restricting direct access to some of an object's components, which is a key part of data hiding.
- 2. Abstraction: Hiding complex implementation details and showing only the essential features of the object. For example, you know how to drive a car (press the gas pedal) without needing to know how the engine works internally.
- 3. Inheritance: A mechanism where a new class (subclass or child class) derives properties and methods from an existing class (superclass or parent class). This promotes code reuse. For example,
Car,Truck, andMotorcycleclasses could all inherit from aVehicleclass.
- 4. Polymorphism: The ability of an object to take on many forms. It allows a single action to be performed in different ways. For example, a
draw()method could be used to draw a circle, a square, or a triangle.
Analogy: Think of a class as a cookie cutter (Dog class). The objects are the cookies you make with it (myDog, yourDog). Each cookie has the same shape, but each can have its own unique decorations (attributes like name). Encapsulation is the cookie itself, bundling the dough and shape. Abstraction is that you just eat the cookie, you don't need to know the recipe. Inheritance is creating a special GingerbreadMan cookie cutter from a basic Person cookie cutter. Polymorphism is telling different animal-shaped cookie cutters to makeSound() and each one makes a different sound.
// This is a blueprint (class) for a Dog
class Dog {
// Attributes (state)
String breed;
int age;
String color;
// Method (behavior)
void bark() {
System.out.println("Woof! Woof!");
}
}
// This is creating an instance (object) of the Dog class
Dog myDog = new Dog();
myDog.age = 5;
myDog.breed = "Golden Retriever";
myDog.bark(); // Calls the method on the objectLesson quiz