6.3.4.?? ??Scala中getClass 和 classOf
Class A extends class B
B b=new A??? b.getClass ==classOf[A]
B b=new B??? b.getClass ==classOf[B]
?
- isInstanceOf 只能判断出对象是否为指定类以及其子类的对象,而不能精确的判断出,对象就是指定类的对象;
- 如果要求精确地判断出对象就是指定类的对象,那么就只能使用 getClass 和 classOf 了;
- p.getClass 可以精确地获取对象的类,classOf[XX] 可以精确的获取类,然后使用 == 操作符即可判断;
- 举例说明:
- Scala中,每个类都可以有一个主constructor和任意多个辅助constructor,而且每个辅助constructor的第一行都必须调用其他辅助constructor或者主constructor代码;因此子类的辅助constructor是一定不可能直接调用父类的constructor的;
package cn.itcast.extends_demo
class Person4 {}
class Student4 extends Person4
object Student4{
? def main(args: Array[String]) {
??? val p:Person4=new Student4
??? //判断p是否为Person4类的实例
??? println(p.isInstanceOf[Person4])//true
??? //判断p的类型是否为Person4类
??? println(p.getClass == classOf[Person4])//false
??? //判断p的类型是否为Student4类
??? println(p.getClass == classOf[Student4])//true
? }
}
?
6.3.5.?? ??Scala中调用父类的constructor
?
- 只能在子类的主constructor中调用父类的constructor。
- 如果父类的构造函数已经定义过的 field,比如name和age,子类再使用时,就不要用 val 或 var 来修饰了,否则会被认为,子类要覆盖父类的field,且要求一定要使用 override 关键字。
- 举例说明:
package cn.itcast.extends_demo
class Person7(val name:String,val age:Int){
? var score :Double=0.0
? var address:String="beijing"
? def this(name:String,score:Double)={
??? //每个辅助constructor的第一行都必须调用其他辅助constructor或者主constructor代码
??? //主constructor代码
????? this(name,30)
????? this.score=score
? }
? //其他辅助constructor
? def this(name:String,address:String)={
????? this(name,100.0)
????? this.address=address
? }
}
class Student7(name:String,score:Double) extends Person7(name,score)
?
6.3.6.?? ??Scala中抽象类
- 如果在父类中,有某些方法无法立即实现,而需要依赖不同的子类来覆盖,重写实现不同的方法。此时,可以将父类中的这些方法编写成只含有方法签名,不含方法体的形式,这种形式就叫做抽象方法;
- 一个类中,如果含有一个抽象方法或抽象field,就必须使用abstract将类声明为抽象类,该类是不可以被实例化的;
- 在子类中覆盖抽象类的抽象方法时,可以不加override关键字;
- 举例说明:
package cn.itcast.extends_demo
abstract class Person9(val name:String) {
? //必须指出返回类型,不然默认返回为Unit
? def sayHello:String
? def sayBye:String
}
classStudent9(name:String) extends Person9(name){
? //必须指出返回类型,不然默认
? def sayHello: String = "Hello,"+name
? def sayBye: String ="Bye,"+name
}
object Student9{
? def main(args: Array[String]) {
??? val s = new Student9("tom")
??? println(s.sayHello)
??? println(s.sayBye)
? }
}
?
6.3.7.?? ??Scala中抽象field
- 如果在父类中,定义了field,但是没有给出初始值,则此field为抽象field;
- 举例说明:
package cn.itcast.extends_demo
abstract class Person10 (val name:String){
//抽象fields
??? val age:Int
}
class Student10(name: String) extends Person10(name) {
?? val age: Int = 50
}