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

Scala 类和对象

La classe è l'astrazione dell'oggetto, mentre l'oggetto è un esempio specifico della classe. La classe è astratta e non occupa memoria, mentre l'oggetto è specifico e occupa spazio di archiviazione. La classe è una bozza per creare oggetti, è un modello software che definisce i metodi e le variabili inclusi in un tipo specifico di oggetto.

Possiamo utilizzare la parola chiave new per creare oggetti di classe, come nell'esempio seguente:

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

Le classi in Scala non vengono dichiarate come public, un file di origine Scala può contenere più classi.

La definizione di classe dell'esempio sopra definisce due variabili x e y Un metodo:moveIl metodo non restituisce alcun valore.

La definizione di classe in Scala può avere parametri, detti parametri di classe, come xc, yc, che possono essere acceduti in tutto il corpo della classe.

Poi possiamo utilizzare new per creare un'istanza di classe e accedere ai metodi e variabili della classe:

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: " + x);
      println("The coordinate point: " + y);
   }
}
object Test {
   def main(args: Array[String]) {
      val pt = new Point(10, 20);
      // Move to a new position
      pt.move(10, 10);
   }
}

执行以上代码,输出结果为:

$ 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:

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

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

  • 3. When 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:

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: " + x);
      println("The coordinate point: " + 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 field 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 position
      loc.move(10, 10, 5);
   }
}

执行以上代码,输出结果为:

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

In Scala, to override a non-abstract method, you 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)
}

执行以上代码,输出结果为:

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

Oggetto singleton in Scala

In Scala, non esiste la parola chiave static, ma ci fornisce anche un metodo di implementazione del pattern singleton utilizzando la parola chiave object.

In Scala, quando si utilizza il pattern singleton, oltre alla definizione della classe, è necessario definire un oggetto object dello stesso nome. La differenza tra l'oggetto object e la classe è che l'oggetto object non può accettare parametri.

Quando un oggetto singleton è associato a una classe con lo stesso nome, viene chiamato oggetto companion di quella classe: companion object. Devi definire sia la classe che il suo oggetto companion nello stesso file di origine. La classe viene chiamata classe companion dell'oggetto singleton: companion class. La classe e il suo oggetto companion possono accedere ai membri privati l'uno dell'altro.

Esempio di oggetto singleton

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("Punto di coordinate x: " + point.x);
         println("Punto di coordinate y: " + point.y);
      }
   }
}

执行以上代码,输出结果为:

$ scalac Test.scala 
$ scala Test
Punto di coordinate x: 10
Punto di coordinate y: 20

Esempio di oggetto companion

/* nome del file: Marker.scala */
 * autore: Base Tutorial Website
 * url: it.oldtoolbag.com
 */
// metodo costruttore privato
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")  
    }
}

执行以上代码,输出结果为:

$ scalac Marker.scala 
$ scala Marker
创建颜色标记:红色
创建颜色标记:蓝色
创建颜色标记:绿色
颜色标记:红色
颜色标记:蓝色