abstract class Computers{
def hdd:String
def RAM:String
def CPU:String
}
class PC(storage:String,memory:String,Cores:String) extends Computers{
def display:String="This is PC"
var device="PC"
def hdd={
"Hard disk"+" "+storage
}
def RAM={
memory
}
def CPU={
Cores
}
}
class LAPTOP(storage:String,memory:String,Cores:String) extends Computers{
def see:String={
"Hi All"
}
var device="Laptop"
def hdd={
storage
}
def RAM={
device +":" +memory+" RAM"
}
def CPU={
Cores
}
}
object Computers{
def apply(compType:String,storage:String,memory:String,Cores:String)={
compType match{
case "PC"=>new PC(storage:String,memory:String,Cores:String)
case "LAPTOP"=>new LAPTOP(storage:String,memory:String,Cores:String)
}
}
def main(args:Array[String]){
val c1=Computers("PC","1 TB","12 GB","5 GHz")
val c2=Computers("LAPTOP","1 TB","12 GB","5 GHz")
println(c1.display)
println(c1.hdd)
println(c2.RAM)
}
}我正在尝试实施工厂的设计模式。但是,当我试图调用子类方法( PC类的显示方法)时,得到了以下编译错误:“值显示不是计算机的成员,”,有人能帮我解释为什么会出现这个错误吗?
发布于 2022-02-24 07:17:35
您将得到此错误,因为当您使用Computers的apply方法时,您将得到一个类型为Computers的实例,该实例没有定义方法display (因为它仅在子类PC上定义)。
如果希望访问此方法,则需要有一个PC类型,而不是一个Computer类型。你可以用几种方式实现这一点。
PC
Computer是一个.asInstanceOf[PC],以便您可以调用该方法(不推荐此方法),因为如果您正在转换的内容实际上不是PC,则在运行时可能会失败。https://stackoverflow.com/questions/71247947
复制相似问题