scala 通过apply创建类的对象
1 package cn.scala_base.oop.scalaobject;
2
3 class Boy(name: String) {
4 private var age: Int = 0;
5
6 println(name);
7
8 def this(name: String, age: Int) {
9 //调用主构造器
10 this(name);
11 this.age = age;
12 }
13
14 }
15
16 /**
17 * 在伴生对象中定义apply方法后可以在创建对象时使用Class(xx)的形式
18 */
19 object Boy {
20 def apply(name: String) = new Boy(name);
21
22 def apply(name: String, age: Int) = new Boy(name, age);
23 }
24
25 object ObwithApply {
26 def main(args: Array[String]): Unit = {
27 val b = Boy("xxx");
28
29 val b2 = Boy("tele", 30);
30 }
31 }