scala 主从构造器

 1 package cn.scala_base.oop.scalaclass
 2 
 3 /**
 4  * 构造器分为两种,一种是主构造器,另一种是从构造器,所有的从构造器必须在其方法体
 5  * 的第一行调用主构造器
 6  *
 7  * Man的主构造器无参数,所以调用时采用this();
 8  */
 9 class Man {
10   var name: String = _;
11   var age: Int = _;
12 
13   //可以有多个从构造器,类似方法重载
14   def this(name: String) {
15     this();
16     this.name = name;
17   }
18 
19   def this(age: Int) {
20     this();
21     this.age = age;
22   }
23   def this(name: String, age: Int) {
24     this(name);
25     this.age = age;
26     //不能再写this(age);会造成重复调用主构造器
27 
28   }
29 
30   //或者
31   /*def this(name:String,age:Int) {
32       this();
33       this.name = name;
34       this.age = age;
35   }*/
36 
37 }
38 
39 //主构造器与类名放在一起,所有未写在方法体(或者说是代码块)中的代码均被视为主构造器的代码,如果主构造器中的参数被方法使用了,
40 //则会被声明成private[this],否则该参数仅仅属于主构造器,与new出的对象无关
41 class Person(name: String) {
42   println(name);
43   private var age = 0;
44 
45   def getName = name;
46 
47   //从构造器
48   def this(name: String, age: Int) {
49     this(name);
50     this.age = age;
51   }
52 
53 }
54 //可以给主构造器的参数设置默认值,这样new的时候可以不用传递参数.如果还被val修饰则不能再被该类的其他方法修改
55 class Person2(val name: String = "yeye") {
56   println(name);
57 
58 }
59 
60 object Constructor {
61   def main(args: Array[String]): Unit = {
62 
63     //主构造器无参,可以省略()
64     val m = new Man;
65 
66     /*val p = new Person("yeye");
67        println(p.getName);*/
68 
69     val p2 = new Person2();
70 
71   }
72 
73 }

 

posted @ 2018-11-29 16:35  tele  阅读(261)  评论(0编辑  收藏  举报