作业:定义一个伴生类和伴生对象Student
定义伴生类Student
属性:name、age、score private权限
定义getter和setter
定义伴生对象Student
定义apply和unapply方法
定义一个object对象,进行测试(分别调用apply方法和unapply方法)
//定义伴生类 Student
class Student{
private var name:String=_
private var age:Int=_
private var score:Double=_
//辅助构造器
def this(name:String,age:Int,score:Double){
this()
this.name=name
this.age=age
this.score=score
}
//定义getter
def _name=name
def _age=age
def _score=score
//定义setter
def name_(name:String): Unit ={
this.name=name
}
def age_(age:Int): Unit ={
this.age=age
}
def score_(score:Double): Unit ={
this.score=score
}
}
//定义伴生对象 Student
object Student{
def apply(name:String,age:Int,score:Double)={
println("自动调用 apply")
new Student(name,age,score)
}
def unapply(stu:Student):Option[(String,Int,Double)]={
println("自动调用 unapply")
Some((stu.name,stu.age,stu.score))
}
}
object New {
def main(args: Array[String]): Unit = {
val stu1:Student=Student("anyiya",20,60.8)
//stu1.show()
stu1 match {
case Student(a,b,c) => println(a,b,c)
}
println(s"getter方法展示:${stu1._name},${stu1._age},${stu1._score}")
println("使用setter方法")
stu1.age_(22)
stu1.score_(97.8)
println(s"getter方法展示:${stu1._name},${stu1._age},${stu1._score}")
}
}
期末测试题
求1~100所有能被3整除的数字和,结果存入D:/data.txt
import java.io.PrintWriter
import scala.io._
object New {
def main(args: Array[String]): Unit = {
var sum=0
for(i <- 0 to 100 ){
if(i %3 ==0)
sum=sum+i
}
var out = new PrintWriter("D:\\data.txt")
out.print(sum)
out.close()
}
}
定义一个Person类
定义一个Action特质,包含一个方法thinking,调用则显示正在思考......
定义一个Persion类,包含一个public的属性name:String,一个无参的主构造器和有参数的辅助构造器。继承Action特质。
trait Action{
def thinking()={
println("正在思考......")
}
}
class Person() extends Action{
var name:String=_
def this(name:String){
this()
this.name=name
}
override def thinking(): Unit = {
print(name)
super.thinking()
}
}
object New {
def main(args: Array[String]): Unit = {
var per1:Person = new Person("anyiya")
per1.thinking()
}
}