Scala classes and objects


A class is an abstraction of an object, and an object is a concrete instance of a class. Classes are abstract and do not occupy memory, while objects are concrete and occupy storage space. A class is a blueprint for creating objects, a software template that defines the methods and variables included in an object of a specific type.

We can use the new keyword to create an object of a class. The example is as follows:

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 ("x 的坐标点: " + x);
      println ("y 的坐标点: " + y);
   }
}

Classes in Scala are not declared as public, and there can be multiple classes in one Scala source file.

The class of the above example defines two variables x and y, and one method: move. The method has no return value.

Scala's class definition can have parameters, called class parameters, such as xc, yc above. Class parameters can be accessed in the entire class.

Then 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 ("x 的坐标点: " + x);
      println ("y 的坐标点: " + y);
   }
}

object Test {
   def main(args: Array[String]) {
      val pt = new Point(10, 20);

      // 移到一个新的位置
      pt.move(10, 10);
   }
}

Execute the above code, the output result is:

$ scalac Test.scala 
$ scala Test
x 的坐标点: 20
y 的坐标点: 30

Scala inheritance

Scala inheriting a base class is very similar to Java, but we need to pay attention to a few points:

  • #1. Override must be used to override a non-abstract method symbol.

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

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

Next let’s look at an 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 ("x 的坐标点: " + x);
      println ("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 ("x 的坐标点 : " + x);
      println ("y 的坐标点 : " + y);
      println ("z 的坐标点 : " + z);
   }
}

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

override val xc Overrides the fields of the parent class.

Inheritance will inherit all properties and methods of the parent class. Scala only allows inheritance of one parent class.

The example is as follows:

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 ("x 的坐标点 : " + x);
      println ("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 ("x 的坐标点 : " + x);
      println ("y 的坐标点 : " + y);
      println ("z 的坐标点 : " + z);
   }
}

object Test {
   def main(args: Array[String]) {
      val loc = new Location(10, 20, 15);

      // 移到一个新的位置
      loc.move(10, 10, 5);
   }
}

Execute the above code, the output result is:

$ scalac Test.scala 
$ scala Test
x 的坐标点 : 20
y 的坐标点 : 30
z 的坐标点 : 20

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

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 result is:

$ 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 is also We provide an implementation method for the singleton pattern, which is to use the keyword object.

When using the singleton mode in Scala, in addition to the defined class, an object object with the same name must also be defined. The difference between it and a class is that the object object cannot take parameters.

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

Single instance object instance

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 ("x 的坐标点 : " + point.x);
         println ("y 的坐标点 : " + point.y);
      }
   }
}

Execute the above code, the output result is:

$ scalac Test.scala 
$ scala Test
x 的坐标点 : 10
y 的坐标点 : 20

Companion object instance

/* 文件名:Marker.scala
 * author:php中文网
 * url:www.php.cn
 */

// 私有构造方法
class Marker private(val color:String) {

  println("创建" + this)
  
  override def toString(): String = "颜色标记:"+ color
  
}

// 伴生对象,与类共享名字,可以访问类的私有属性和方法
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"))  
        // 单例函数调用,省略了.(点)符号  
		println(Marker getMarker "blue")  
    }
}

Execute the above code, the output result is:

$ scalac Marker.scala 
$ scala Marker
创建颜色标记:red
创建颜色标记:blue
创建颜色标记:green
颜色标记:red
颜色标记:blue