Introduction to OOPS in Scala
Think about an employee management application. You need to store employee details such as name, age, department and salary. You also need operations to update employee information, calculate salaries and generate reports.
One way to build this application is to write separate variables and functions for every operation. That might work initially, but as the application grows, managing everything becomes difficult.
Wouldn't it be better if we could keep related data and the operations performed on that data together?
This is where Object-Oriented Programming (OOP) becomes useful.
1. What is Object-Oriented Programming?
Object-Oriented Programming is a programming approach where we organize an application around objects.
An object represents something that has:
State: The data or properties it holds.
Behaviour: The operations or actions it can perform.
For example, an employee has a name, department and salary. The employee can also perform actions such as displaying details or calculating annual salary.
Instead of managing these things separately, OOP allows us to group them together.
2. Procedural Programming vs Object-Oriented Programming
Let's understand the difference with a simple example.
Suppose we want to calculate the annual salary of an employee.
In a procedural approach, we might write:
val employeeName = "Deepak"
val monthlySalary = 80000.0
def calculateAnnualSalary(salary: Double): Double = salary * 12
println(calculateAnnualSalary(monthlySalary))This works perfectly fine for a small program.
However, imagine managing 500 employees, each with different details and operations. You would need to organize and maintain a lot of separate data and functions.
With OOP, we can bring related data and behaviour together.
class Employee( val name: String, val monthlySalary: Double):
def calculateAnnualSalary(): Double = monthlySalary * 12
val employee = new Employee("Deepak", 80000.0)
println(employee.calculateAnnualSalary())Output:
960000.0
Now the employee's information and its related behaviour are maintained together.
| Procedural Programming | Object-Oriented Programming |
|---|---|
| Organizes code around functions and procedures | Organizes code around objects |
| Data and operations are often separate | Data and behaviour can be grouped |
| Suitable for smaller, straightforward tasks | Useful for modelling larger applications |
| Reuse often happens through functions | Reuse can involve classes, inheritance and composition |
Neither approach is universally better. The right choice depends on the problem. Scala supports both styles.
3. Understanding Classes and Objects
Two concepts form the foundation of OOP: classes and objects.
Class: A class is a blueprint that defines the properties and behaviour of objects.
Object: An object is an instance of a class. It contains actual values for the properties defined by that class.
Consider a simple example:
class Employee( val name: String, val department: String):
def displayDetails(): Unit =
println(s"Employee: $name")
println(s"Department: $department")
val employee1 = new Employee("Deepak", "IT")
val employee2 = new Employee("Rahul", "Finance")
employee1.displayDetails()
employee2.displayDetails()Output:
Employee: Deepak
Department: IT
Employee: Rahul
Department: Finance
Here, Employee is the class, while employee1 and employee2 are two different objects created from that class.
Both objects share the same structure but hold different data.
4. The Four Pillars of OOP
OOP is commonly explained through four important concepts. These concepts help developers build applications that are easier to maintain, extend and reuse.
1. Encapsulation
Encapsulation means keeping data and related operations together while controlling how internal data is accessed or modified.
For example, a bank account should not allow anyone to directly change its balance. Deposits and withdrawals should happen through controlled methods.
We'll explore this in detail in upcoming chapter.
2. Inheritance
Inheritance allows one class to reuse and extend the functionality of another class.
For example, a Manager and a Developer may share common employee information but have their own specific behaviour.
We'll explore this in upcoming chapter.
3. Polymorphism
Polymorphism allows different objects to respond to the same operation in their own way.
For example, a payment system can process credit card, UPI and net banking payments through a common payment operation.
We'll explore this in upcoming chapter.
4. Abstraction
Abstraction means exposing what an object can do while hiding unnecessary implementation details.
For example, when you make a payment, you care about initiating the payment and receiving its result. You don't need to understand every internal processing step.
We'll explore this in upcoming chapter.
5. How Does Scala Support OOP?
Scala is a multi-paradigm programming language. It supports both object-oriented programming and functional programming.
You can create classes, objects, inheritance hierarchies and traits just like you would expect in an object-oriented language.
However, Scala also provides features such as immutable values, higher-order functions and pattern matching that encourage functional programming.
Here are some important OOP features in Scala:
| Feature | Purpose |
|---|---|
class | Defines a class |
object | Defines a singleton object |
extends | Establishes inheritance |
trait | Defines reusable behaviour and contracts |
abstract class | Defines a class that cannot be instantiated directly |
override | Replaces an inherited concrete implementation |
private | Restricts access to members |
One important difference from Java is that Scala has a dedicated object construct for singleton objects. You don't need to create a separate static class to hold utility methods.
6. When Should You Use OOP?
OOP is particularly useful when an application contains different entities with their own data and behaviour.
Consider these examples:
Banking: Accounts, customers, transactions and payment methods.
Ecommerce: Products, customers, orders and inventory.
Employee Management: Employees, managers, departments and payroll.
Healthcare: Patients, appointments, doctors and medical records.
Enterprise Applications: Users, roles, permissions and services.
The goal is not to create a class for everything. The goal is to choose meaningful objects that make the application easier to understand and maintain.
