Lesson 6

Understanding Object-Oriented Programming in Scala

Topic Overview

Hello! Today, we're going to solidify our understanding of Object-Oriented Programming (OOP) in Scala by revisiting the pillars of Encapsulation, Abstraction, Inheritance, and Polymorphism. Let's get started!

Revisiting the Fundamentals

We'll revisit OOP fundamentals. As you may know, we create objects from classes, which define attributes (data) and methods (operations). Remember that the keyword this refers to the object's methods and properties that are called.

Here's a quick refresher:

1class Person: 2 var name: String = "John Doe" 3 def introduce() = 4 // In this context, "this" references the "name" of the current Person object. 5 println(s"Hello, my name is ${this.name}.")
Exploring the Four OOP Principles

Now, let's go back to the central principles of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism.

Encapsulation protects data by making attributes private and providing safe methods for access.

Abstraction simplifies systems by creating higher-level representations.

Inheritance allows classes to inherit properties and methods, encouraging code reusability.

Polymorphism allows different types of objects to be handled in a uniform manner if they share some features.

Below is an example demonstrating polymorphism and inheritance:

1abstract class Animal: 2 def makeSound() = 3 println("The animal makes a sound") 4 5class Pig extends Animal: 6 override def makeSound() = 7 println("Oink! Oink!")

In this example, Pig, a subclass of Animal, overrides the makeSound method, showcasing polymorphism.

Practical Examples

To solidify our understanding, let's examine some practical Scala examples.

First, an Employee class showcases encapsulation:

1class Employee(private var name: String, private var salary: Double): 2 def getName: String = 3 // getName provides safe access to the name attribute 4 name 5 6 def getSalary: Double = 7 // Similarly, getSalary provides safe access to the salary attribute 8 salary 9 10 def raiseSalary(percent: Double): Unit = 11 if percent > 0 then 12 // We can safely modify the private salary attribute within the class 13 salary += salary * percent / 100.0

An abstract class is used to illustrate abstraction:

1abstract class Drawable: 2 def draw(): Unit 3 4class Circle(private val radius: Double) extends Drawable: 5 override def draw(): Unit = 6 // Circle implements the abstract requirement of the Drawable interface 7 println(s"Drawing a Circle with a radius of $radius")
Quick Lesson Summary

To summarize, we've revised the implementation of the four pillars of OOP in Scala — encapsulation, abstraction, inheritance, and polymorphism — and noted their implementation in practical examples. Our next step is putting this knowledge into practice. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.