zoukankan      html  css  js  c++  java
  • 主构造器

    // 1.主构造器的参数直接放置在类名之后
    // 2.主构造器会执行类定义中的所有语句
    class Person(val name: String, val age: Int) {
      private val props = new Properties
      props.load(new FileReader("xxx.properties"))
      // 上述语句是主构造器的一部分
    }
    
    
    // 1.构造参数也可以是普通的方法参数,不带val或者var
    class Person2(name: String,age: Int){
      def description = name + " is " + age + " years old"
      // 上述代码声明并初始化了不可变字段name和age,而这两个字段都是对象私有的.
      // 类似这样的字段等同于private[this] val字段的效果
    }
    

    针对主构造器参数生成的字段和方法

    主构造器参数 生成的字段或方法
    name:String 对象私有字段.如果没有方法使用name,则没有该字段
    private val/var name:String 私有字段,私有的getter/setter方法
    val/var name:String 私有字段,公有的getter/setter方法
    @BeanProperty val/var name:String 私有字段,公有的scala和java版本的getter/setter方法
    // 如果想让主构造器变成私有的,可以像这样放置privtate关键字
    // 这样一来用户就必须通过辅助构造器来构造Person对象
    class Person3 private(val id: Int){}
    
  • 相关阅读:
    leetcode 34 rust
    leetcode 2 rust
    leetcode 1 rust
    leetcode 20 rust
    leetcode 287 rust
    leetcode 18 rust
    lottery抽奖
    webpack
    webpack(7)-生产环境
    webpack(6)-模块热替代&tree shaking
  • 原文地址:https://www.cnblogs.com/dongdone/p/6894080.html
Copyright © 2011-2022 走看看