Scala 特质(Trait)
2024-04-23 09:44:00 阅读次数:40
ide,Scala,父类
1 package chapter06
2
3 object Test13_Trait {
4 def main(args: Array[String]): Unit = {
5 val student: Student13 = new Student13
6 student.sayHello()
7 student.study()
8 student.dating()
9 student.play()
10 }
11 }
12
13 // 定义一个父类
14 class Person13 {
15 val name: String = "person"
16 var age: Int = 18
17 def sayHello(): Unit = {
18 println("hello from: " + name)
19 }
20 def increase(): Unit = {
21 println("person increase")
22 }
23 }
24
25 // 定义一个特质
26 trait Young {
27 // 声明抽象和非抽象属性
28 var age: Int
29 val name: String = "young"
30
31 // 声明抽象和非抽象的方法
32 def play(): Unit = {
33 println(s"young people $name is playing")
34 }
35
36 def dating(): Unit
37 }
38
39 class Student13 extends Person13 with Young {
40 // 重写冲突的属性
41 override val name: String = "student"
42
43 // 实现抽象方法
44 def dating(): Unit = println(s"student $name is dating")
45
46 def study(): Unit = println(s"student $name is studying")
47
48 // 重写父类方法
49 override def sayHello(): Unit = {
50 super.sayHello()
51 println(s"hello from: student $name")
52 }
53
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/reliableyang/5651544,作者:靠谱杨的挨踢IT生活,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。
上一篇:剑指Offer【39】-- 平衡二叉树
下一篇:IK分词器