English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Classes and Objects

A class is an abstraction of an object, and an object is a concrete instance of a class. A class is abstract and does not occupy memory, while an object is concrete and occupies storage space. A class is a blueprint used to create objects, which is a software template defining the methods and variables included in objects of a specific type.

We can use the new keyword to create class objects, as shown in the 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("The coordinate point of x: " + x);
      println("The coordinate point of y: " + y);
   }
}

Scala classes are not declared as public, and a Scala source file can have multiple classes.

The class definition in the above example defines two variables x and y A method:moveMethods do not have a return value.

Scala class definitions can have parameters, called class parameters, such as the above xc, yc. Class parameters can be accessed throughout the class.

Next, we can use new to instantiate the class and access the methods and variables in the class:

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("The coordinate point of x: " + x);
      println("The 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, the output will be:

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

Scala inheritance

Scala inheritance is similar to Java, but we need to pay attention to the following points:

  • 1To override a non-abstract method, you must use the override modifier.

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

  • 3When you override an abstract method of the superclass in the subclass, you do not need to use the override keyword.

Let's take a look at an example next:

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("The coordinate point of x: " + x);
      println("The 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("The coordinate point of x: "); + x);
      println("The coordinate point of y: "); + y);
      println("The coordinate point of z : " + z);
   }
}

Scala uses the extends keyword to inherit a class. In the example, the Location class inherits from the Point class. Point is called the superclass (base class), and Location is called the subclass.

override val xc It overrides the fields of the superclass.

Inheritance inherits all properties and methods of the superclass, Scala only allows inheritance from one superclass.

Here is an 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("The coordinate point of x: "); + x);
      println("The 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("The coordinate point of x: "); + x);
      println("The coordinate point of y: "); + y);
      println("The 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, the output will be:

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

Scala must use the override modifier to rewrite a non-abstract method.

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, the output will be:

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

Scala Singleton Object

In Scala, there is no such thing as static, but it also provides an implementation method for the singleton pattern, which is to use the keyword object.

In Scala, when using the singleton pattern, in addition to defining the class, you also need to define an object with the same name. The difference between the object and the class is that the object cannot take parameters.

When a singleton object shares the same name with a class, it is called the companion object of that class: companion object. You must define the class and its companion object in the same source file. The class is called the companion class of the singleton object: companion class. The class and its companion object can access each other's private members.

Singleton Object 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("The coordinate point of x: "); + point.x);
         println("The coordinate point of y: "); + point.y);
      }
   }
}

Execute the above code, the output will be:

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

Companion Object Example

/* Filename: Marker.scala
 * author:Basic Tutorial Website
 * url:www.oldtoolbag.com
 */
// Private Constructor
class Marker private(val color: String) {
  println("Create" + this)
  
  override def toString(): String = "Color Tag:"+ color
  
}
// Companion 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"))  
        // Singleton function call, the dot (.) symbol is omitted  
                println(Marker.getMarker("blue"))  
    }
}

Execute the above code, the output will be:

$ scalac Marker.scala 
$ scala Marker
Create Color Tag: red
Create Color Tag: blue
Create Color Tag: green
Color Tag: red
Color Tag: blue