From 43876f15af475f76199f9c49b6223e39446c064e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BD=97=E7=A5=A5?= <1366971433@qq.com> Date: Thu, 9 May 2019 18:05:37 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=A7=E6=89=BF=E5=92=8C=E7=89=B9=E8=B4=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/Scala类和对象.md | 2 +- notes/Scala继承和特质.md | 82 +++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 notes/Scala继承和特质.md diff --git a/notes/Scala类和对象.md b/notes/Scala类和对象.md index 8405909..c361f60 100644 --- a/notes/Scala类和对象.md +++ b/notes/Scala类和对象.md @@ -64,7 +64,7 @@ object Person { ### 2.1 成员变量可见性 -Scala中成员变量的可见性默认都是public,但是为了保证其不被外部干扰,建议声明为private,并通过getter和setter方法进行访问。 +Scala中成员变量的可见性默认都是public,如果想要保证其不被外部干扰,可以声明为private,并通过getter和setter方法进行访问。 ### 2.2 getter和setter属性 diff --git a/notes/Scala继承和特质.md b/notes/Scala继承和特质.md new file mode 100644 index 0000000..a435f87 --- /dev/null +++ b/notes/Scala继承和特质.md @@ -0,0 +1,82 @@ +# 继承和特质 + +## 一、继承 + +### 1.1 extends & override + +父类Person: + +```scala +class Person { + + + var name = "" + + // 1.不加任何修饰词,默认为public,能被子类和外部访问 + var age = 0 + + // 2.使用protected修饰的变量能子类访问,但是不能被外部访问 + protected var birthday = "" + + // 3.使用private修饰的变量不能被子类和外部访问 + private var sex = "" + + + def setSex(sex: String): Unit = { + this.sex = sex + } + + // 4.重写父类的方法建议使用override关键字修饰 + override def toString: String = name + ":" + age + ":" + birthday + ":" + sex + +} +``` + +使用`extends`关键字实现继承: + +```scala +// 1.使用extends关键字实现继承 +class Employee extends Person { + + override def toString: String = "Employee~" + super.toString + + // 2.使用public或protected关键字修饰的变量能被子类访问 + def setBirthday(date: String): Unit = { + birthday = date + } + +} +``` + +测试继承: + +```scala + +object ScalaApp extends App { + + val employee = new Employee + + employee.name = "heibaiying" + employee.age = 20 + employee.setBirthday("2019-03-05") + employee.setSex("男") + + println(employee) +} + +// 输出: Employee~heibaiying:20:2019-03-05:男 +``` + +### 1.2 调用父类构造器 + + + +### 1.3 构造顺序和提前定义 + + + +二、抽象类 + + + +二、特质 \ No newline at end of file