类的定义与使用
```scala
package com.gosuncn
object Person {
def main(args: Array[String]): Unit = {
val student = new Student()
println(student.name + ".." + student.age)
student.eat
student.name = "Apollo"
student.tellAge
student.tellAddress
}
}
class Student {
var name: String = _
var age: Int = 10
private[this] val address: String = "beijing"
def eat(): Unit = {
println(name + " eating ...")
}
def tellAge(): Unit = {
println(name + " age is " + age)
}
def tellAddress(): Unit = {
println(name + " address is " + address)
}
}
```
主构造器
```scala
package com.gosuncn
object Person {
def main(args: Array[String]): Unit = {
val apollo = new Student("Apollo", 38)
apollo.printInfo()
val paul = new Student("Paul", 40,"M")
paul.printInfo()
}
}
class Student(var name: String, var age: Int) {
var gender: String = "Unknown"
/**
* 附属构造器
*/
def this(name: String, age: Int, gender: String) {
this(name, age)
this.gender = gender
}
println("Student Starting ...")
def printInfo(): Unit = {
println(name + "," + age + "," + gender)
}
println("Student Ending ...")
}
```
继承
```scala
package com.gosuncn
object Test {
def main(args: Array[String]): Unit = {
val student = new Student("Apollo", 29, "Beijing")
println(student.age)
}
}
class Person(var name: String, var age: Int) {
println("Person Starting ...")
println(name + "," + age)
println("Person Ending ...")
}
class Student(name: String, age: Int, address: String) extends Person(name, age) {
println("Student Starting ...")
println(name + "," + age + "," + address)
println("Student Ending ...")
}
```
重写
```scala
package com.gosuncn
object Test {
def main(args: Array[String]): Unit = {
println(new Person("Apollo", 33))
}
}
class Person(var name: String, var age: Int) {
override def toString: String = {
"name:" + name + " age:" + age
}
}
```