Skip to main content
HomeTutorialsScala

Scala Classes and Objects

In this tutorial, you will learn about the fundamental notions of object-oriented programming in Scala: Classes and Objects.
Oct 2019  · 8 min read

DataCamp has recently launched their first Scala course: Introduction to Scala. Check it out!

Also, check out the following tutorials:

Introduction

oops concepts diagram
Source

In general, Object-Oriented Programming (OOP) consists of classes and objects and aims to implement real-world entities like polymorphism, inheritance.

OOPs makes development way faster and cheaper with better software maintainability. The primary reason for this magic is the number of features it supports; you have classes & objects which can easily be re-used in the future based on the requirement, in contrast to a program that lacks classes & objects. This, in turn, leads to higher-quality software, which is also extensible with new methods and attributes.

Let's say; you have a showroom of cars; every few months down the line, a new car is launched, and to inform the audience about its name and features, you have to define new methods, attributes from scratch. However, if you have an object-oriented program that has a class car, all you will add is an object for that new car, which will call the class methods & attributes with the information of the vehicle.

The class can be thought of as a representation or a design for objects. Classes will usually have their own methods (behavior) and attributes.

Attributes are individual entities that differentiate each object from the other and determine various qualities of an object. Methods, on the other hand, are more like how a function usually operates in programming. They determine how the instance of the class works. It's mostly because of methods (behavior); objects have the power to be done something to them.

Source

The above figure gives you more intuition about the flow of object-oriented programming or, to be more specific, what a class looks like. In the above picture, there is a class car which has attributes: fuel, max speed, and can have more attributes like the model, make, etc. It has different sets of methods like refuel(), getFuel(), setSpeed(), and some additional methods can be change gear, start the engine, stop the engine, etc.

So, when you talk about a specific car, you would have an object, which is an instantiation of a class.

Now, let's talk about object-oriented programming in Scala.

Classes and Objects in Scala

Much like c++ and java, object-oriented programming in Scala follows pretty much the same conventions. It has the concept of defining classes and objects and within class constructors, and that is all there is to object-oriented programming in Scala.

Class Declaration

class Class_name{
// methods and attributes
}

Class in Scala is defined by the keyword class followed by the name of the class, and generally, the class name starts with a capital letter. There are few keywords which are optional but can be used in Scala class declaration like: class-name, it should begin with a capital letter: superclass, the parent class name preceded by extend keyword: traits, it is a comma-separated list implemented by the class preceded by extend keyword.

A class can in Scala inherits only one parent class, which means Scala does not support multiple inheritances. However, it can be achieved with the use of Traits.

Finally, the body of a class in Scala is surrounded by curly braces {}.

// Name of the class is Car
class Car
{

    // Class variables
    var make: String = "BMW"
    var model: String = "X7"
    var fuel: Int = 40

    // Class method
    def Display()
    {
        println("Make of the Car : " + make);
        println("Model of the Car : " + model);
        println("Fuel capacity of the Car : " + fuel);
    }
}
object Main  
{

    // Main method
    def main(args: Array[String])  
    {

        // Class object
        var obj = new Car();
        obj.Display();
    }
}

You can save the above code by the name class.scala and run it on the terminal as scala class.scala, and you should see the output as below.

output

Well, the above code does not completely utilize the privileges an object-oriented program is capable of. Since the output of the above code will return the same result irrespective of how many times you run. You defined static variables inside the class, and the values of those variables will remain constant, even if you create infinite new objects. In conclusion, you cannot expect it to give you details for a Mercedes Benz or a Ferrari car.

Constructor in Scala

Constructors are mainly used to initialize the object state. This object initializing happens at the time of object creation, and they are called only once.

There are two types of constructors in Scala: Primary and Auxiliary. For this tutorial, you will learn about the primary constructor (Source: O'Reilly).

class Class_name(Parameter_list){
// methods, attributes
}

The primary constructor contains the same body with the class, and it is created implicitly along with the class definition. It begins at the class definition and spans the complete body of the class. Also, when there is only one constructor in the Scala program, it is known as a primary constructor. A primary constructor can be defined with zero, one, or more parameters.

So, let's take the previous example, but this time append the primary constructor feature into it and observe the effect.

Also, here you will learn a new feature of a class, i.e., a class can have multiple objects or instances but both independent of each other.

// Name of the class is Car
class Car(make: String, model: String, fuel: Int)
{

    // Class method
    def Display()
    {
        println("Make of the Car : " + make);
        println("Model of the Car : " + model);
        println("Fuel capacity of the Car : " + fuel);
    }
}

object Main

{

    // Main method
    def main(args: Array[String])  
    {

        // Multiple Class object
        var obj1 = new Car("BMW", "X7", 40);
        var obj2 = new Car("Mercedes Benz", "S350D", 50);
        obj1.Display();
        obj2.Display();
    }
}

Let's quickly see the output:

output

Well, isn't this great? With the help of a constructor, you were able to generate more effective results.

Declaring Objects in Scala

Declaring objects in Scala can also be termed as instantiating a class or invoking a class. Similar to classes, objects are also a fundamental unit of object-oriented programming.

An object can consist of three features (Source: GeeksforGeeks:

  • State: Attributes of an object represent it. It also reflects the properties of an object.
  • Behavior: Methods of an object represent it. It also reflects the response of an object with other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

Consider Dog as an object and see the below diagram for its identity, state, and behavior.

diagram
(Source)

All the instances or objects share the class attributes and methods. A single class can have multiple objects, as you learned here. However, the state or values of each object are unique.

Finally, you will write a code that will have primary constructors, class variables, attributes, and methods all combined into a single code.

Below is a pictorial representation of the components put together in the class Motorcycle.

class components

The below code is pretty self-explanatory; on a high-level, though, it checks whether the motorcycle engine is on or off. Initially, the engine is put to an off state, and it will notify you of its state and switch it on.

class Motorcycle(make:String,color:String) {


       var engineState: Boolean = false;

       def startEngine() {
          if (engineState == true){
            println("The engine is already on.");
          }
          else {
            engineState = true
            println("The engine is now on.");
         }
       }

       def showAtts() {
         println("This motorcycle is a "+ color + " " + make);
         if (engineState == true){
           println("The engine is on.");
         }
         else{
            println("The engine is off.");
         }
      }

}
object Main
{
    def main (args: Array[String])
    {
        var m = new Motorcycle("BMW K 1600 GTL","White");
        println("Calling showAtts...");
        m.showAtts();
        println("------");
        println("Starting engine...");
        m.startEngine();
        println("------");
        println("Calling showAtts...");
        m.showAtts();
        println("------");
        println("Starting engine...");
        m.startEngine();
    }
}
diagram

Congratulations!

Congratulations on finishing this tutorial.

You now know how to declare classes and methods, instantiating objects, set their attributes, and call instance methods in Scala. These concepts will be useful to you in not only Scala but even in other programming languages.

Object-oriented programming concepts are interesting and at the same time, very powerful. It adds a new dimension to your code, makes it re-usable. As your program becomes larger, your code will grow in complexity. There is a lot of meat in object-oriented programming concepts like inheritance, polymorphism, instance methods. Another powerful feature is Singleton. The design principles help keep your code more structured and readable. For more on design patterns, consider reading this book.

Please feel free to ask any questions related to this tutorial in the comments section below.

Finally, don't forget to take the new Scala course on DataCamp, Introduction to Scala.

Topics

Learn more about Scala

Course

Introduction to Scala

3 hr
23.1K
Begin your journey with Scala, a popular language for scalable applications and data engineering infrastructure.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Basics of Functions and Methods in Scala

Learn about the basics of methods, named arguments, default parameter values, variable arguments in addition to different kinds of functions.

Olivia Smith

10 min

Scala Traits

Learn about the use of traits in Scala with the help of syntactic examples.
Aditya Sharma's photo

Aditya Sharma

6 min

Variables in Scala

Learn about Scala's variables, rules for defining variables, different types of variables with multiple declaration and assignments along with the scope of a variable.

Olivia Smith

10 min

Lists in Scala

Learn what lists are and how they can be leveraged in the Scala Programming Language.
Aditya Sharma's photo

Aditya Sharma

6 min

Operators in Scala

Learn about the different operators used in the Scala programming language.
Aditya Sharma's photo

Aditya Sharma

6 min

IF ELSE in Scala

In this tutorial, you'll learn about conditional IF ELSE statements in the Scala programming language.
Aditya Sharma's photo

Aditya Sharma

5 min

See MoreSee More