Scala中的类

Scala中类的定义

Scala也是面向对象的语言,所以类的定义与java中的区别并不太大,核心内容都有,只是语法不太一样

在Scala中,编译器默认会生成getter、setter的方法,所有不需要手动编写。但是getter、setter的生成跟字段的可变性与可见性有关,所以getter、setter方法与var、val、private、这三个关键字有关

这里记录下修饰符的规则与getter、setter方法的生成规则:

  • 对于var修饰的参数:外部可读/可改写 (实际上是:编译器为该类参数(字段)自动生成了getter和setter)
  • 对于val修饰的参数:外部可读/不可改写(实际上是:编译器为该类参数(字段)只生成了getter没有生成setter)
  • 对于private var修饰的参数:内部可读/可改写 (编译器不会为私有类参数(字段)自动生成getter和setter)
  • 对于private val修饰的参数:内部可读/不可改写 (编译器不会为该类参数(字段)自动生成getter和setter)
  • 如果连var/val也没有,则字段对外不可见,同时内部只读,不可改写,即默认是:private val
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.anthony

/**
* @ Description:
* @ Date: Created in 21:26 09/07/2018
* @ Author: Anthony_Duan
*/
object class_test {

def main(args: Array[String]): Unit = {
val one = new People()
one.name = "anthony"
one.eat()
one.eat("橘子")
one.info()


val student = new Student("anthony",20)
println(student.name+" "+student.age+" "+student.school)

val student2 = new Student("anthony",20,"male")
println(student2.name+" "+student2.age+" "+student2.school+" "+student2.gender)

}


}

class Student(val name:String,val age:Int){ //主构造器

val school = "Neusoft"

var gender:String = _

def this (name:String,age:Int,gender:String){//附属构造器
this(name,age) //附属构造器的第一句必须调用主构造器或者其他构造器
this.gender =gender
}


}
class People{

var name:String = _ // _ 为占位符 此时变量的类型不能省略
val age = 20

private [this] val gender = "male" // private[this] 权限修饰符

def eat(): Unit ={
println(name+"在吃饭")
}

def eat(food:String)={
println(name+"在吃"+food)
}


def info ()={
println(name+"\n"+age+"\n"+gender)
}

}

Scala中类的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.anthony

/**
* @ Description:
* @ Date: Created in 21:26 09/07/2018
* @ Author: Anthony_Duan
*/
object class_test {

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

val student3 = new Student("anthony",20,"male")

println(student3.name+" "+student3.age+" "+student3.gender)

}
}

class Student(name:String,age:Int,var gender:String)extends People(name:String){
}

class People(var name:String){
val age = 20

def eat(): Unit ={
println(name+"在吃饭")
}

def eat(food:String)={
println(name+"在吃"+food)
}
}

abstract抽象类与重写字段和方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.anthony

/**
* @ Description:
* @ Date: Created in 09:26 10/07/2018
* @ Author: Anthony_Duan
*/
object abstract_test {

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

val stu = new ST()
stu.sleep
}

}

abstract class People{

val name:String

val gender:String

def eat

def sleep
}

class ST extends People{

override val name: String = "Anthony"

override val gender: String = "male"

override def eat=
{println("实现eat")}

override def sleep={
println("实现sleep")
}


}
-------------End Of This ArticleThank You For Reading-------------