Scala classes and objects


Release date:2023-11-21 Update date:2023-11-22 Editor:admin View counts:295

Label:

Scala classes and objects

A class is an abstraction of an object, and an object is a concrete instanceof a class. Classes are abstract and do not take up memory, while objects are concrete and take up storage space. A class is a blueprint for creating objects, and it is a software template that defines methods and variables included in a particular type of object.

We can use it. new keyword to create an object of the class, as an example:

Example

class Point(xc: Int, yc: Int) {
   var x: Int = xc
   var y: Int = yc
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Coordinate point of x: " + x);
      println ("Coordinate point of y: " + y);
   }
}

Classes in Scala are not declared as public , there can be multiple classes in a single Scala source file

The class of the above example defines two variables x and y , one way is : move , the method does not return a value.

The class definition of Scala can have parameters, called class parameters, such as xc and yc above, which can be accessed throughout the class.

And then we can use new to instantiate the class and access the methodsand variables in the class:

Example

import java.io.\_
class Point(xc: Int, yc: Int) {
   var x: Int = xc
   var y: Int = yc
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Coordinate point of x: " + x);
      println ("Coordinate point of y: " + y);
   }
}
object Test {
   def main(args: Array[String]) {
      val pt = new Point(10, 20);
      // Move to a new location
      pt.move(10, 10);
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
Coordinate point of x: 20
Coordinate point of y: 30

Scala inheritance

Scala inherits a base class that is similar to Java, but we need to note thefollowing:

  • 1.Rewriting a non-abstract method must use the override modifier.

  • 2.Only the main constructor can write parameters to the constructor of the base class.

  • 3.When overriding abstract methods of a superclass in a subclass, you do not need to use the override keyword.

Let’s take a look at an example:

Example

class Point(xc: Int, yc: Int) {
   var x: Int = xc
   var y: Int = yc
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Coordinate point of x: " + x);
      println ("Coordinate point of y: " + y);
   }
}
class Location(override val xc: Int, override val yc: Int,
   val zc :Int) extends Point(xc, yc){
   var z: Int = zc
   def move(dx: Int, dy: Int, dz: Int) {
      x = x + dx
      y = y + dy
      z = z + dz
      println ("Coordinate point of x : " + x);
      println ("Coordinate point of y : " + y);
      println ("Coordinate point of z : " + z);
   }
}

Scala usage extends keyword to inherit a class. In the instance Location class inherits from the Point class. Point called parent class (base class) Location is called a subclass.

override val xc: Overrides the fields of the parent class.

Inheritance inherits all the properties and methods of the parent class, andScala allows only one parent class to inherit.

Examples are as follows:

Example

import java.io.\_
class Point(val xc: Int, val yc: Int) {
   var x: Int = xc
   var y: Int = yc
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Coordinate point of x: " + x);
      println ("Coordinate point of y: " + y);
   }
}
class Location(override val xc: Int, override val yc: Int,
   val zc :Int) extends Point(xc, yc){
   var z: Int = zc
   def move(dx: Int, dy: Int, dz: Int) {
      x = x + dx
      y = y + dy
      z = z + dz
      println ("Coordinate point of x : " + x);
      println ("Coordinate point of y : " + y);
      println ("Coordinate point of z : " + z);
   }
}
object Test {
   def main(args: Array[String]) {
      val loc = new Location(10, 20, 15);
      // Move to a new location
      loc.move(10, 10, 5);
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
Coordinate point of x : 20
Coordinate point of y: 30
Coordinate point of z : 20

Scala rewrites a non-abstract method and must use the override modifier.

Example

class Person {
  var name = ""
  override def toString = getClass.getName + "[name=" + name + "]"
}
class Employee extends Person {
  var salary = 0.0
  override def toString = super.toString + "[salary=" + salary + "]"
}
object Test extends App {
  val fred = new Employee
  fred.name = "Fred"
  fred.salary = 50000
  println(fred)
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
Employee[name=Fred][salary=50000.0]

Scala singleton object

In Scala, there is no static , but it also provides us with away to implement the singleton pattern, which is to use keywords object .

When using the singleton pattern in Scala, in addition to the defined class,define a class with the same name object object, the difference between it and a class is object object cannot take parameters.

When a singleton object shares the same name with a class, it is called a companion object of that class: companion object . You must define the class and its companion objects in the same source file. Class iscalled the companion class of this singleton object: companion class .Class and its companion objects can access their private members to each other.

Singleton object instance

Example

import java.io.\_
class Point(val xc: Int, val yc: Int) {
   var x: Int = xc
   var y: Int = yc
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
   }
}
object Test {
   def main(args: Array[String]) {
      val point = new Point(10, 20)
      printPoint
      def printPoint{
         println ("Coordinate point of x: " + point.x);
         println ("Coordinate point of y : " + point.y);
      }
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
Coordinate point of x : 10
Coordinate point of y : 20

Accompanying object instance

Example

/* file name:Marker.scala
 * author:Novice Tutorial
 * url:www.runoob.com
 */
//Private Construction Method
class Marker private(val color:String) {
  println("create" + this)

  override def toString(): String = "color mark:"+ color

}
// Accompanying object, with the same name as the class, can access the private properties and methods of the class
object Marker{

    private val markers: Map[String, Marker] = Map(
      "red" -> new Marker("red"),
      "blue" -> new Marker("blue"),
      "green" -> new Marker("green")
    )

    def apply(color:String) = {
      if(markers.contains(color)) markers(color) else null
    }


    def getMarker(color:String) = {
      if(markers.contains(color)) markers(color) else null
    }
    def main(args: Array[String]) {
        println(Marker("red"))
        // Single instance function call, omitted (dot) symbol
                println(Marker getMarker "blue")
    }
}

Execute the above code, and the output is as follows:

$ scalac Marker.scala
$ scala Marker
Create color markers:red
Create color markers:blue
Create color markers:green
Color markers:red
Color markers:blue

Powered by TorCMS (https://github.com/bukun/TorCMS).