Black monkey house: Scala abstract class

Abstract keyword tag can not be instantiated. The method of label-abstract, as long as the method body can be dispensed with. Class can have abstract fields, field abstract field is no initial value.
Abstract class can have an abstract field can have non-abstract field
can have abstract methods, may also have non-abstract methods

1, a subclass of abstract class implementing

//抽象类
abstract class Person4 {
  val name: String
  def log(msg:String): String
}

class Student1 extends Person4{
  override val name: String = "Nick"
  override def log(msg: String): String = {
    println(msg)
    msg
  }
}

2, anonymous subclass implementation of the abstract class

object Main5 extends App{

  //使用匿名内部类的方式 实现接口
  val p1 = new Person4 {
    override def log(msg: String): String = {println(msg);msg}
    override val name: String = "Sick"
  }

  println(p1)
  println(p1.log("haha"))
  println(p1.name)
}

尖叫提示:子类实现抽象方法不需要override,简单说override是可以省略的,但是写上override是规范

Reproduced in: https: //www.jianshu.com/p/35376f17decc

Guess you like

Origin blog.csdn.net/weixin_33890526/article/details/91182496