您的位置:首页 > 其它

scala学习——类

2016-03-08 22:17 281 查看

1.简单类和无参方法

class person{
private var name = "Joe"
private var age = 20
def yourName() = name
def yourage = age
def increment(){
age +=1
}
def myprint():Unit={
println(name+" is "+age+" years old !")
}
}


1).在scala中,类并不声明为public。scala源文件中可以包含多个类,故这些类具有公有可见性;

2).字段必须初始化;

3).方法默认是公有的;

4).调用无参方法时,可以写圆括号,也可以不写。通常我们对取值器省略括号,而改值器使用括号。如:调用以上程序中increment()时使用括号,二调用myprint方法时不使用括号。

5).若对于无参方法,定义时,没有使用圆括号,在调用时也不能使用圆括号。

2.带getter和setter的属性

A.默认的getter和setter方法

class student{
var id = 1001
}


*在scala中,每个字段都提供getter和setter方法,分别为:id 和 id_=。若字段为公有(public),则其getter、setter方法也是公有的;若字段为私有(private),则其getter、setter方法也是私有的。

B.自定义getter和setter方法

class student {
private var id = 1001
def id = id
def id_= (newId :Int){
if(id>1001) id = newId
}
}


C.只带getter属性

如果属性的值构建后,就不在改变,则可以使用val定义字段。

class student {
val city = "Beijing"
...
}


此时,Scala会生成一个final字段和一个getter方法,但没有setter方法。

D.Bean属性

当我们将Scala字段标注为@BeanProperty时,getFoo/setFoo方法会自动生成。如:

import scala.reflect.BeanProperty
class student {
@BeanProperty var name:String = _
}


此时将会生成如下四个方法:

(1).name:String

(2).name_=(newName:String):Unit

(3).getName():String

(4).setName(newName:String):Unit

3.构造器

A.辅助构造器

1).辅助构造器的名称都为this。(当我们修改类名的时候,不必向JAVA和C++一样来修改构造器)

2).每个辅助构造器都必须以一个先前以定义的其他辅助构造器或主构造器的调用开始。

*如果一个类没有显式地定义一个主构造器,则自动拥有一个无参的主构造器。

class Student{
private var id = 101
private var name = "no name"

def this (id:int){ //辅助构造器
this() //调用主构造器
this.id = id
}
def this (id:int,name:String){ //辅助构造器
this(id) //调用上一个辅助构造器
this.name = name
}
}


B.主构造器

1).主构造器参数直接放在类名之后。如:

class Student(var id :int,var name:Stirng){
...
}


当我们实例化一个对象时,val stu = new Student(101,”Joe”),这样即完成了调用主构造器,实例化一个stu对象,并且stu.id = 101 ,stu.name=”Joe”,同时,还默认实现了id和name的getter、setter方法。

2).主构造器会执行类定义中的所有语句。如:

class Student(var id:int,var name:String){
println(name+"'s id is "+id)//在调用主构造器时,该语句也被执行
}


3).我们通常可以通过在主构造器中使用默认参数来避免过多地使用辅助构造器。如:

class Student(var id:int,var name:String ,var city="Beijing"){
...
}


4.嵌套类

在Scala中,我们可以在类中嵌套类,在函数中嵌套函数。以下是类中定义类的示例:

import scala.collection.mutable.ArrayBuffer
class Network{
class Member(val name:String){
val contacts = new ArrayBuffer[Member]
}
private val menbers = new ArrayBuffer[Member]
def join (name:String){
val m = new Member(name)
menbers += m
m
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: