Scala – Classes and Objects

  • Post category:Scala
  • Reading time:8 mins read

Classes and Objects

Classes and Objects are basic concepts of Object Oriented Programming .

What is an Object ?

Well It is the most basic concept and a key to understand the Object-Oriented programming . Object is an entity that has two characteristics , State and Behavior . Some examples of real world object can be : Bike , Chair , Dog etc. Lets take an example of a Bike . Bike has some state ( current gear , current speed ) and behavior ( change gear , apply brake ) . One way to begin thinking in an object-oriented way is to identify the state and behavior of real world objects . Software objects are also similar to the real world objects. They too contains State and Behavior . An Object stores its state in fields and exposes the behavior through methods.

What is a Class ?

Class is a blueprint from which objects of same type can be created . Lets take an example of a Bike again . There are thousands of bikes with the same characteristics i.e having same make and model . They are created from the same prototype / blueprint called class.

Example

class Counter {
   private var count = 0 // Must initialize
   def inc() {
      count += 1
   }

   def currentVal() = { count }
}

object CounterExample {
   def main(args: Array[String]) {
      // Creating object of class Counter.
      val count = new Counter()
      println("Old Counter Value :" + count.currentVal()) 
      count.inc() 
      count.inc() 
      println("New Counter Value :" + count.currentVal())
   }
}

In the above example, we have a class Counter having a field count two methods inc() and currentVal().

Output

Old Counter Value :0
New Counter Value :2

Class Constructor

Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary.

Example – Primary Constructor

// Defining parameters in a class constructor automatically creates fields in the class
class Duck(val size: Int, val age: Int) 

object ConstructorExample extends App {
   var d = new Duck(10, 20)
   println(d.size+ " " + d.age)
}

Example – Auxiliary Constructor

class Person(val firstName: String, val lastName: String, val age: Int) {
   // Auxiliary constructor.
   def this(firstName: String, lastName: String) {
      this(firstName, lastName, 0); // Calling the primary constructor.
   }
}

object AuxiliaryConstructor {
   def main(args: Array[String]) {
      // Use the primary constructor
      val person1= new Person("Prakash", "Pr", 29)
      println(person1.firstName)

     // Use a Auxiliary constructor 
     val person2= new Person("Fred", "Thomas") 
     println(person2.firstName)
  }
}  

Output

Prakash
Fred

Inheritance – Extending a Class

Inheritance is the capability of one class to acquire the common state and behavior of another class while adding its own functionality . In Object Oriented programming , the concept of inheritance provides the idea of re-usability . This means we can add additional features to a class without modifying it.We can extend a base Scala class and can design an inherited class in the same way we do it in Java .

Example

class Item(var price: Double, var description: String) {
   // Override toString() method of AnyRef Class.
   override def toString(): String = {
      description + " Cost: " + discountedPrice
   }

   // No discounted price
   def discountedPrice(): Double = { price }
}

class SpecialItem(price: Double, description: String, discountPercent: Double) extends Item(price, description) {
   // A val in Superclass cannot be overridden by var or def in subclass
   override def discountedPrice(): Double = { price - ((discountPercent / 100) * price) }
}

object Inheritance {
   def main(args: Array[String]): Unit = {
      val item = new Item(45.6, "Book") 
      println(item) 
      val specialItem = new SpecialItem(100, "Sepcial Book", 10) 
      println(specialItem)
   }
}

Output

Book Cost: 45.6
Sepcial Book Cost: 90.0

Explanation

  • Item is the parent class containing two attributes price and description and contains a method discountedPrice.
  • SpecialItem class extends Item and overrides the method discountedPrice.
  • We must use override keyword when we override a method of parent class.

Implicit Classes

Implicit classes allow implicit conversations with class’s primary constructor when the class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is introduced in Scala 2.10. Implicit class is always in the object scope where all method definitions are allowed because implicit class cannot be a top level class.

Example

Let us take an example of an implicit class named IntTimes with the method times(). It means the times () contain a loop transaction that will execute the given statement in number of times that we give. Let us assume the given statement is “4 times println (“Hello”)” means the println (“”Hello”) statement will execute 4 times.

The following is the program for the given example. In this example two object classes are used (Run and Demo) so that we have to save those two classes in different files with their respective names as follows.

Run.scala − Save the following program in Run.scala.

object ImplicitHelper {
   implicit class loopNTimes(x: Int) {
      def times[A](f: => A): Unit = {
         def loop(current: Int): Unit =
            if (current > 0) {
               f
               loop(current - 1)
            }
         loop(x)
      }
   }
}

And we can import the above implicit class as follows

import ImplicitHelper._
object ImplicitHelperTest{
   def main(args: Array[String]) {
      5 times println("HI")
   }
}

Output

HI
HI
HI
HI
HI

NOTE:

  • Implicit classes must be defined inside another class/object/trait (not in top level).
  • Implicit classes may only take one non –implicit argument in their constructor.
  • Implicit classes may not be any method, member or object in scope with the same name as the implicit class.

Singleton Objects

Singleton object is a class that has exactly one instance. It is created lazily when it is referenced, like a lazy val.

Example

object ReservationCounter {
   private var lastNum=0
   def generateReservationNumber()={
      lastNum = lastNum+1
      lastNum
   }
}

In the above example, ReservationCounter is a Singleton object.