2017-08-29 181 views
0

我正在從JavaTpoint中練習此代碼以學習Scala中的繼承。但是我無法從班級車輛中獲取成員自行車的價值初始化爲零。我嘗試了超類型引用,但它仍然顯示overriden值。你能告訴我如何使用Bike類的一個實例訪問速度值= 0。這裏是代碼和輸出。 預先感謝。如何使用子類的實例訪問超類的成員

class Vehicle{ 
    val speed = 0 
    println("In vehicle constructor " +speed) 
    def run(){ 
     println(s"vehicle is running at $speed") 
    } 
} 

class Bike extends Vehicle{ 
    override val speed = 100 
    override def run(){ 
    super.run() 
     println(s"Bike is running at $speed km/hr") 
    } 
} 

object MainObject3{ 
    def main(args:Array[String]){ 
     var b = new Bike() 
     b.run() 
     var v = new Vehicle() 
     v.run() 
     var ve:Vehicle=new Bike() 
     println("SuperType reference" + ve.speed) 
    ve.run() 
    } 
} 

How do I get the result using instance of Bike.

回答

1

我能想到的兩種選擇。

1)在覆蓋它之前保存該值。

class Bike extends Vehicle{ 
    val oldspeed = speed 
    override val speed = 100 
    override def run(){ 
    println(s"Vehicle started at $oldspeed km/hr") 
    println(s"Bike is running at $speed km/hr") 
    } 
} 

2)在基類中設置值爲def。然後它可以在子類中訪問。

class Vehicle{ 
    def speed = 0 
    def run(): Unit = {...} 
} 

class Bike extends Vehicle{ 
    override val speed = 100 
    override def run(){ 
    println(s"Vehicle started at ${super.speed} km/hr") 
    println(s"Bike is running at $speed km/hr") 
    } 
} 
+0

1)將值保存到新字段將根據將其保存在不同的內存位置。它避開了訪問。 2)重寫def作品! – Learner