package examples class Person { val publicVal = 1 //自动生成getter var publicVar = 2 //自动生成getter和setter //自定义getter和setter private var privateAge=0 def age = privateAge //getter def age_=(newValue:Int) //setter { if(newValue>privateAge) privateAge = newValue } } /* * 主构造器 */ class Person1(name:String,age:Int) //这样name和age都默认是val { def info=println("name:"+name+",age:"+age) } class Person11(val name:String,private var age:Int) { def info=println("name:"+name+",age:"+age) } /* * 辅助构造器 */ class Person2() { private var name="" private var age=0 def this(name:String)= { this()//调用默认主构造器 this.name=name } def this(name:String,age:Int) { this(name)//调用另一个构造器 this.age=age } } object Example5 { def main(args: Array[String]) { val person = new Person person.age=1//调用age的setter方法 println(person.publicVal)//调用getter方法 val person1 =new Person1("linger",24)//调用主构造器 person1.info val person2 = new Person2("linger")//调用辅助构造器 new Person2//调用默认的无参主构造器 } }
1 name:linger,age:24
原文:http://blog.csdn.net/lingerlanlan/article/details/43455585