zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    升级2010
    如何修改MSSQL的用户名
    减小delphi体积的方法
    Delphi调用大漠插件示例
    Delphi 7升级到XE2的字符串问题
    MSSQL 清空数据库中表的数据
    MSSQL 2008 密钥
    springboot 2.1.4 多数据源配置
    springboot 数据库连接 解决驼峰命名问题
    Flask 热更新
  • 原文地址:https://www.cnblogs.com/tele-share/p/10039284.html
Copyright © 2011-2022 走看看