[修饰符] class 类名 {
类体
}
object Test{
def main(args: Array[String]): Unit = {
val cat = new Cat
cat.name = "小白"
cat.age = 3
cat.color = "白色"
}
}
class Cat {
var name: String = _
var age = 0
var color: String = ""
}
class 类名(形参列表) { // 主构造器 类名定义
// 类体
def this(形参列表) { // 辅助构造器
}
def this(形参列表) { //辅助构造器可以有多个...
}
}
object Test{
def main(args: Array[String]): Unit = {
val person = new Person
person.showInfo()
val person1 = new Person("zs", 12)
person1.showInfo()
val person2 = new Person("zs")
person2.showInfo()
val person3 = new Person(24, "zs")
person3.showInfo()
//class私有 val cat: Cat = new Cat//主构造器调用报错(无参)
val cat: Cat = new Cat("kk", 1)
cat.showInfo()
// val og: Dog = new Dog("nn")//直接调用主构造函数报错
val dog: Dog = new Dog("nn", 10)
dog.showInfo()
}
}
class Person { // 会生成一个默认的无参构造器
var name: String = _
var age: Int = _
println("主构造器会执行类定义中的所有语句") //由于上面创建了4个对象,会被打印4次
def this(name: String, age: Int) {
this
// this.name = name
// this.age = age
}
def this(name: String) {
//所有的辅助构造器必须调用主构造器 => 为了底层能够实现对父类的初始化
this()
println(name)
this.name = name
}
def this(age: Int, name: String) {
this
this.name = name
this.age = age
}
def showInfo(): Unit = {
println("person信息如下:")
println("name=" + this.name)
println("age=" + this.age)
}
}
class Cat private() { //主构造函数无参
var name: String = _
var age: Int = _
def this(name: String, age: Int) {
this()
this.name = name
this.age = age
}
def showInfo(): Unit = {
println("cat:")
println("name=" + this.name)
println("age=" + this.age)
}
}
class Dog private(dName: String) {//主构造函数含参 dName
var name: String = dName
var age: Int = _
def this(name: String, age: Int) {
this(name)
this.age = age
}
def showInfo(): Unit = {
println("dog:")
println("name=" + this.name)
println("age=" + this.age)
}
}
输出结果:
主构造器会执行类定义中的所有语句
person信息如下:
name=null
age=0
主构造器会执行类定义中的所有语句
person信息如下:
name=null
age=0
主构造器会执行类定义中的所有语句
zs
person信息如下:
name=zs
age=0
主构造器会执行类定义中的所有语句
person信息如下:
name=zs
age=24
cat:
name=kk
age=1
dog:
name=nn
age=10
object Test{
def main(args: Array[String]): Unit = {
val car = new Car
car.name = ""
car.setName("Mercedes")
car.setColor("black")
printf("carName:%s\n", car.getName)
printf("carColor:%s", car.getColor)
}
class Car {
//默认生成 public name() 和 public name_$eq
//如果加入了@BeanProperty 注解,就会再生成 public getName() 和 public setName()
@BeanProperty
var name: String = _
@BeanProperty
var color: String = _
}
}
输出结果:
carName:Mercedes
carColor:black
object Test{
def main(args: Array[String]): Unit = {
var p: Person = new Person("小倩", 20)
}
}
class Person {
var age: Int = 90
var name: String = _
def this(n: String, a: Short) {
this()
this.name = n
this.age = a
}
}