标签:另一个 实现继承 指定 模式 object 类的属性 语言 一个 div
class Person { private val name = "Weiking" def getName = name } class Student extends Person { def getAge= 26 } object test{ def main(args: Array[String]): Unit = { val stu=new Student printf(stu.getName,stu.getAge) } }
class Person1 { val age = 48 def getName = "Weiking" } class Student1 extends Person1 { override val age = 20 override def getName="jack" // 重写父类方法 def ParentMember =println("我父亲的名字是 "+ super.getName,"我父亲今年"+super.age) //super调用父类的方法getName可以,调用父类的字段age就会报错 def selfMember =println("我的名字是 "+ getName,"我今年"+age) } object test{ def main(args: Array[String]): Unit = { val stu=new Student1 stu.ParentMember //Error:(19, 73) super may be not be used on value age stu.selfMember } }
person.isInstanceOf[Person]
person.asInstanceOf[Student]
class Person{} class Student extends Person{} object Test { def main(args: Array[String]): Unit = { val person =new Student println(person.isInstanceOf[Person]) println(person.isInstanceOf[Student]) if (person.isInstanceOf[Student]){ val stu =person.asInstanceOf[Student] }
注意1:isInstanceOf新版本已被弃用改用模式匹配
注意2:如果对象是null,则isInstanceOf一定返回false,asInstanceOf一定返回null
class Person{} class Student extends Person{} object Test { def main(args: Array[String]): Unit = { val p: Person = new Student var s: Student = null println(p.isInstanceOf[Student]) println(s.isInstanceOf[Student]) println(s.asInstanceOf[Student]) } }
class Person{} class Student extends Person{} class Teacher extends Person{} object Test { def main(args: Array[String]): Unit = { val p: Person = new Student p match { case pe: Teacher => println("person对象") case stu: Student => println("student对象") } } }
class Person{} class Student extends Person{} object Test { def main(args: Array[String]): Unit = { val person: Person = new Student val ob: Class[_ <: Person] = person.getClass val cla: Class[Student] = classOf[Student] if (person.getClass == classOf[Person]) println("True") else println("false") if (person.getClass == classOf[Student]) println("True") else println("false") if(1.getClass==classOf[Int]) println("True") else println("false") } }
标签:另一个 实现继承 指定 模式 object 类的属性 语言 一个 div
原文地址:https://www.cnblogs.com/WeiKing/p/11662882.html