当前位置:网站首页>Level 2: polymorphism
Level 2: polymorphism
2022-04-22 08:35:00 【True question OK】
Task description
Our mission : The topic of this section is to take the mobile phone brand as an example , understand Scala For method rewriting and polymorphism in object-oriented programming, please read the following carefully “ Related knowledge ” The content in , Understand what needs to be done for each mobile phone class , completion huawei Functions in class , Make the program run as expected .
Related knowledge
In order to complete this mission , You need to master :1. How to override methods ,2. How to achieve polymorphism .
##### Method rewriting
Method rewriting refers to when a subclass inherits from its parent class , Methods inherited from the parent class cannot meet their own needs , Subclasses want to have their own implementation , At this time, you need to override the methods of the parent class (override), Method rewriting is the key to realize polymorphism and dynamic binding .Scala Method rewriting and Java Method rewriting in language is the same , through override Keyword to override the method in the parent class , So as to realize the processing logic of the subclass itself .
class Phone(var phoneBrand:String,var price:Int){
// For the parent class Any Medium toString Method
override def toString=s"Phone($phoneBrand,$price)"
}
class Apple(phoneBrand:String,price:Int,var place:String)extends Phone(phoneBrand,price){
// For the parent class Phone Medium toString Method
override def toString=s"Apple($phoneBrand,$price,$place)"
}
object TestPhone{
def main(args:Array[String]){
// call Apple Class's own toString Method returns the result
println(new Apple("iphone",5400,"Shenzhen"))
}
}
Running results :Apple(iphone,5400,shenzhen)
If you don't override the parent class toString Method , The returned result is the class name plus hashcode value , for example :
scala> class Phone(var phoneBrand:String,var price:Int)
defined class Phone
scala> new Phone("HuaWei",4500)
res1: Phone = Phone@55881f40
Polymorphism and inheritance
After implementing inheritance , A child class can have the properties and methods of the parent class , You can also add new class members to the subclass or override the methods in the parent class . Polymorphism is a language feature implemented on the basis of inheritance , It refers to allowing different objects to respond to the same message , That is to say, the same message can adopt different behavior modes according to different sending objects .
Polymorphism is also called dynamic binding or delayed binding , It refers to determining the actual type of the referenced object during execution rather than compilation , Call its corresponding method according to its actual type , In other words, the reference of the subclass can be assigned to the parent class , When the program runs, it calls the corresponding method according to the actual type . The main function of polymorphism is to eliminate the coupling relationship between types . There are three necessary conditions for polymorphism : There must be inheritance ; There should be rewriting ; The parent class reference points to the subclass object .
// Define parent class Phone
class Phone(var phoneBrand:String,var price:Int){
def buy():Unit=println("buy() method in Phone") //buy Method , No parameter
//compare Method , Parameter is Phone type
def compare(p:Phone):Unit=println("compare() method in Phone")
}
// Defining subclasses Apple
class Apple( phoneBrand:String,price:Int) extends Phone(phoneBrand,price){
private var AphoneNo:Int=0
// Override parent class compare Method
override def compare(p:Phone):Unit={
println("compare() method in Apple")
println(this.phoneBrand+" is compared with "+p.phoneBrand)
}
}
If you create Apple Class object , Parent class Phone The reference points to the object :
val p1:Phone=new Apple("iphone",6400)
Use parent class reference p1 call compare Method , Then what is really called is the subclass Apple Rewritten in compar Method ; If the parent class references p1 call buy Method , Because of subclasses Apple The... In the parent class is not overridden in buy Method , Will undoubtedly call... In the parent class buy Method .
#### Programming requirements
The programming task of this pass is to complete... According to the expected results HuaWei Class from Phone Functions inherited by class , Consider whether you need to rewrite each method .
Test instructions
The following is a description and sample test of how the platform evaluates the functions you have implemented .
Test input : No input
Expected results :buy() method in HuaWeicompare() method in HuaWeihuawei is compared with iphone-----------------------------buy() method in Phonecompare() method in Appleiphone is compared with huawei
Start your mission , wish you success !
object TestPhone{
// Define parent class Phone
class Phone(var phoneBrand:String,var price:Int){
def buy():Unit=println("buy() method in Huawei") //buy Method , No parameter
//compare Method , Parameter is Phone type
def compare(p:Phone):Unit=println("compare() method in Huawei")
}
// Defining subclasses Apple
class Apple( phoneBrand:String,price:Int) extends Phone(phoneBrand,price){
private var AphoneNo:Int=0
// Override parent class compare Method
override def buy():Unit=println("buy() method in Phone")
override def compare(p:Phone):Unit={
println("compare() method in Apple")
println(this.phoneBrand+" is compared with "+p.phoneBrand)
}
}
// Defining subclasses 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*************************
}
// Operation entrance
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 The reference is Apple Object of type ,Apple Class is not on the buy Method , Therefore, what it calls is... Inherited from the parent class buy Method */
p2.buy()
//p2.compare(p1) The actual type passed in is HuaWei, It's called Apple After class rewriting compare Method
p2.compare(p1)
}
}
版权声明
本文为[True question OK]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220743122556.html
边栏推荐
猜你喜欢
Introduction to smarttablayout

CentOS 安裝 MySQL

Simple use of fresco - simpledraweeview

cesium实现建筑物单体化(分栋分层)

指针和字符串

kubernetes学习笔记

手把手教你实现RecyclerView的下拉刷新和上拉加载更多
![[paper reading] [3D object detection] voxel set transformer: a set to set approach to 3D object detection from point clouds](/img/49/255f46e44039500acf1c4a641f5c91.png)
[paper reading] [3D object detection] voxel set transformer: a set to set approach to 3D object detection from point clouds
![[paper reading] [3D target detection] pvgnet](/img/fc/7fd22bbc1aaf4bc5ae38543cd03ae3.png)
[paper reading] [3D target detection] pvgnet

7-34 delete duplicate characters (set usage) & 7-35 count the number of characters (unordered_map)
随机推荐
Flutter基础
Cesium加载地形数据(cesiumlab制作地形数据),从源数据到地形服务
The map cutter can cut the picture into tile data. Its main purpose is to cut the high-definition satellite image into tile map. It can be used for offline map development based on Mercator coordinate
Navicat Premium 导入SQL文件
Shell 命令脚本
Flutter Foundation
shell学习笔记——shell对输出流的处理awk
[no very low code] low code platform development diary, SQL programming of low code platform
QT designer, jump, layout, style
构造函数与toString
【论文阅读】【3d目标检测】pvgnet
VirtualBox虚拟机(甲骨文Oracle VM )
二进制的前导的零
Airtest installation and introduction
CentOS 安装 MySQL
Machine learning notes - Mathematics in principal component analysis
Spark SQL gets the element at an index of the array
指针和字符串
微服务(分布式架构)
Asnotracking for efcore optimization