定义一个类,包含field以及方法
calss HelloWorld{
private var name = "HEL"
def sayHello(){print("HEllo,"+name)} //在类中不叫函数 叫方法
def getName = name
}
//创建类的对象,并调用其方法
val helloworld =new HelloWorld
helloword.sayHello()
print(helloworld.getname)//如果方法在定义的时候不带括号,那么在调用的时候也不能带括号
定义不带private的 var field ,此时Scala生成的面向JVM的类时,会定义为private的name字段,并提供public的getterhe setter方法;
如果使用private修饰field,则生成的getter和setter也是private的
如果定义val field,则只会生成getter方法
如果不希望生成setter和getter方法,则将field声明为private【this】
class Student{
var name = “LEO”
}
调用getter和setter方法,分别叫做name和name_=
val leo = new Student
print(leo.name)
leo.name="leo 1"