第一关:
编程要求
本关的编程任务是补全huawei
类中从 Phone 类继承的函数,以使得程序运行结果如预期输出。根据提示,在右侧编辑器补充代码。
测试说明
下面是对平台如何评测你所实现功能的说明及样例测试。
测试输入:无输入
预期结果:Welcome to use Apple Phone!
This is a/an Apple phone. It is expensive.
Welcome to use HuaWei Phone!
This is a/an HuaWei phone. It is useful.
abstract class Phone{
val phoneBrand: String
def info()
def greeting() {
println("Welcome to use phone!")
}
}
class Apple extends Phone{
override val phoneBrand = "Apple"
def info() {
printf("This is a/an %s phone. It is expensive.\n", phoneBrand)
}
override def greeting() {
println("Welcome to use Apple Phone!")
}
}
class HuaWei extends Phone {
override val phoneBrand = "HuaWei"
def info() {
printf("This is a/an %s phone. It is useful.\n", phoneBrand)
}
//**************Begin*************************
override def greeting(){
printf("Welcome to use %s Phone!\n",phoneBrand)
}
//**************End**************************
}
object MyPhone {
def main(args: Array[String]){
val myPhone1 = new Apple()
val myPhone2 = new HuaWei ()
myPhone1.greeting()
myPhone1.info()
myPhone2.greeting()
myPhone2.info()
}
}
第二关:多态
任务描述
本关任务:本关主题是以手机品牌为例,理解Scala面向对象编程中方法重写和多态请仔细阅读下面“相关知识”中的内容,理解每个手机类所需完成的操作,补全huawei
类中的函数,使得程序运行结果如预期输出。
object TestPhone{
//定义父类Phone
class Phone(var phoneBrand:String,var price:Int){
def buy():Unit=println("buy() method in Phone") //buy方法,无参数
//compare方法,参数为Phone类型
def compare(p:Phone):Unit=println("compare() method in Phone")
}
//定义子类Apple
class Apple( phoneBrand:String,price:Int) extends Phone(phoneBrand,price){
private var AphoneNo:Int=0
//重写父类compare方法
override def compare(p:Phone):Unit={
println("compare() method in Apple")
println(this.phoneBrand+" is compared with "+p.phoneBrand)
}
}
//定义子类HuaWei
class HuaWei(phoneBrand:String,price:Int) extends Phone(phoneBrand,price){
private var HphoneNo:Int=0
//**************Begin*************************
override def buy():Unit=println("buy() method in HuaWei")
override def compare(p:Phone):Unit={
println("compare() method in HuaWei")
println(this.phoneBrand+"is compared with "+p.phoneBrand)
}
//**************Begin*************************
}
//运行入口
def main(args: Array[String]){
val p1:Phone=new HuaWei("huawei",4500)
val p2:Phone=new Apple("iphone",6400)
p1.buy()
p1.compare(p2)
println("-----------------------------")
/*p2引用的是Apple类型的对象,Apple类未对父类中的buy方法进行重写,因此它调用的是继承自父类的buy方法*/
p2.buy()
//p2.compare(p1)传入的实际类型是HuaWei,调用的是Apple类重写后的compare方法
p2.compare(p1)
}
}