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_democlass Person4 {}class Student4 extends Person4object 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 } }
只能在子类的主constructor中调用父类的constructor。如果父类的构造函数已经定义过的 field,比如name和age,子类再使用时,就不要用 val 或 var 来修饰了,否则会被认为,子类要覆盖父类的field,且要求一定要使用 override 关键字。举例说明: package cn.itcast.extends_democlass 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)
转载于:https://www.cnblogs.com/mediocreWorld/p/11367071.html
