您的位置:首页 > 其它

scala第九天Class

2017-03-01 00:00 113 查看
主类:

package com.learn.scala.day9

/**
* Created by zhuqing on 2017/2/28.
*/
object Day9Class {
def main(args: Array[String]): Unit = {
/**
* 初始化类时,可以用括号也可以不用括号
* var person = new Person()
*/
val person = new Person
//实际调用的是 name_=(String)
person.name = "Tom"
//实际调用的是 age_=(Int)
person.age = 12
//如果方法没有参数,可以不写括号
person incrementAge;
//person.age实际调用的方法是age()
println("age=" + person.age)
person incrementAgeNoBody;
println("age=" + person.age);

//实际调用的是方法 call_=(call:String)
person.call = "old man"

println(person.name + " is " + person.call)

person.setId("11-01")

val robbie = new Person
robbie.setId("11-02")
robbie.name = "robbie"

//@BeanProperty默认生成的Java式的get,set方法
robbie.setSchoolName("BeiFang")
println(robbie.getSchoolName)
//标注为@BeanProperty后,默认的get,set方法存在
robbie.schoolName = "NanFang"
println(robbie.schoolName)
}
}

Person类:

package com.learn.scala.day9

import scala.beans.BeanProperty

/**
* Scala的类与Java的类似,scala中默认为公开类
* Created by Robbie on 2017/2/28.
*/
class Person {

/**
* 属性默认为公开,但是必须给默认值,这点不像Java
* Java类中的属性一般为私有,让后提供公开get/set方法,但Scala中不提倡这样中,
* Scala认为这样纯粹是多写代码,浪费时间。
* Scala默认生成get,set 方法,
*  1.例如age , get方法:age(),set方法age_=(Int),
*  2.如果属性是私有的,生成的方法也是私有的。
* 如果属性是公有的,生成的方法也是公有的。
*  3.对val的属性只会生成get方法
*
*/
var name: String = ""
var age: Int = 0
//called 是私有的
private var called: String = "";

/**
* Scala提供了比Java更严的访问限制, private[this]表示,只能在当前实例中使用
*/
private[this] var id = ""

/**
* //@BeanProperty会自动生成Java规范的get,set方法
* 标注为@BeanProperty后,原来默认的get,set方法存在
*/
@BeanProperty var schoolName: String = ""

/**
* 设置Id
*
* @param id
*/
def setId(id: String): Unit = {
this.id = id
}

/**
* called 的get方法
*
* @return
*/
def call = called

/**
* called的set方法
*
* @return
*/
def call_=(call: String) = {
if (age < 10) {
called = "child"
} else if (age < 20) {
called = "boy"
} else if (age < 30) {
called = "man"
} else {
called = call
}

}

/**
* 方法默认公开
*/
def incrementAge(): Unit = {
age = age + 1
}

/**
* 方法的简写可以不带括号
*/
def incrementAgeNoBody = age = age + 1

override def equals(obj: Any): Boolean = {
val other = obj.asInstanceOf[Person]
//other.id 报错,因为Id是private[this],尽管class相同,但不能在其他实例中使用,
//other.called是可以调用的
if (!this.called.equals(other.called)) {
false
} else if (!this.name.equals(other.name)) {
false
} else {
true
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Scala