scala之伴生对象的继承

 

1、定义父类

package cn.qianfeng

class demo_extends {
    def main(args: Array[String]): Unit = {

    }

}

class Annimal{  //定义父类
    protected var name:String =_
    var age:Int = _

    def show: Unit ={   // 父类中的方法
        println(s"name=${name}, age=${age}")
    }

    def this(name:String, age:Int){  // 辅助构造器
        this
        this.name=name
        this.age = age
    }
}

class

2、定义子类用于继承父类

package cn.qianfeng

object demo_extends {
    def main(args: Array[String]): Unit = {
        val a = new Annimal("animan",11)  // 辅助构造器中传参
        val d = new Dog("dog",12)
        a.show
        d.show
    }

}

class Annimal{  //定义父类
    protected var name:String =_
    private var height:Int = _  // 子类无法修改父类中私有变量
    var age:Int = _

    def show: Unit ={   // 父类中的方法
        println(s"name=${name}, age=${age}")
    }

    def this(name:String, age:Int){  // 辅助构造器
        this
        this.name=name
        this.age = age
    }
}

class Dog extends Annimal{  // 子类继承父类,使用extends关键字
    age = 16   // 子类修改父类中的变量
    name = "gougou"  // 子类修改父类中的变量

    def this(name:String, age:Int){
        this
        this.name = name
        this.age = age
    }

    // 重写父类中的方法
    override def show: Unit = {  // 重写父类中的方法必须加override
        super.show
        println("子类中的方法")
    }
}

 

posted on 2021-08-11 13:56  孔扎根  阅读(85)  评论(0编辑  收藏  举报

导航