Scala Abstract Classjava
scala定義抽象類git
抽象類是不能被實例化的ide
一個含有抽象方法的類必須定義成抽象類,也就是使用abstract關鍵字來定義類ui
抽象類能夠有抽象類型(type)this
抽象類能夠包含抽象字段spa
...............................
scala
下面是一個簡單的抽象類的定義code
/** * * @param name * @param age */ abstract class Staff(name: String, age: Int) { /** * scala中的抽象字段 */ var _department: String def department: String = _department def department_=(newValue: String): Unit = _department = newValue /** * 定義參數爲空,返回值爲Unit的抽象方法 */ def doWork(): Unit /** * 抽象方法 * @param value * @return */ def echo(value: String): String def work() = { println("start work") this.doWork() println("work end") } }
下面是對上面父類的繼承和實現orm
/** * 只有子類的主構造器能夠調用父類的主構造器 * @param name * @param age * @param address */ class NormalStaff(name: String, age: Int, address: String) extends Staff(name: String, age: Int) { override var _department: String = _ def this(name: String, age: Int) { this(name, age, "UNKNOW"); } // 實現父類的抽象方法 override def doWork(): Unit = { println("I'm doing some job") } /** * 抽象方法 * 必須使用override關鍵字 * @param value * @return */ override def echo(value: String): String = value override def toString = "NormalStaff [name=" + this.name + ",age=" + this.age + ",department=" + this._department + "]" }
class Food abstract class Animal { type SuitableFood <: Food def eat(food: SuitableFood) } class Grass extends Food class Cow extends Animal { type SuitableFood = Grass override def eat(food: Grass) {} }
使用type關鍵字定義一個抽象類型,type SuitableFood,並指明他的上界是 Food。繼承
abstract class Abstract { type T def transform(x: T): T val initial: T var current: T } class Concrete extends Abstract { override type T = String override def transform(x: T): T = x + x //在Java裏這是final變量,因此必需要初始化賦值 override val initial: T = "string" //在Java裏這個private類型變量,在scala中能夠yoga下劃線賦值 override var current: T = _ }
在這個例子中使用type關鍵字定義了抽象類型T,在實現類中要覆寫並指明抽象類型的具體類型 override type T = String
abstract class Abstract { type T def transform(x: T): T val initial: T var current: T }
在這裏用val和var定義的成員變量都沒有初始化,通過scala的編譯後的字節碼,反編譯後在java類裏都是抽象方法
C:\WorkSpace5-gitosc\scala-sample\out\production\scala-sample\com\usoft3>javap -p Abstract.class Compiled from "test.scala" public abstract class com.usoft3.Abstract { public abstract java.lang.Object transform(java.lang.Object); public abstract java.lang.Object initial(); public abstract java.lang.Object current(); public abstract void current_$eq(java.lang.Object); public com.usoft3.Abstract(); }
=====================
val initial: T var current: T
對應的java類的抽象方法就是,
public abstract java.lang.Object initial(); public abstract java.lang.Object current();
================END================