微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

scala之构造器详解

 

1、基本语法:

构造器分为主构造器和辅助构造器

class 类名(形参列表) {  // 主构造器

   // 类体

   def  this(形参列表) {  // 辅助构造器

   }

   def  this(形参列表) {  //辅助构造器可以有多个...

   }

}

//1. 辅助构造器 函数名称this, 可以有多个,编译器通过不同参数来区分

2、主构造器

class Person(val age:Int,var name:String, sex:Int, score1:Int) {
  var score = score1
  print("主构造器")
}

object Person{
  def main(args: Array[String]): Unit = {
    new Person(3,"zhangsan",1,88)
  }
}

执行结果:

 

反编译:

public class Person

{

  private final int age;

  private int score;

 

  public int age() //get

  {

    return this.age;

  }

 

  public String name() //get

  {

    return this.name;

  }

 

  public void name_$eq(String x$1) //set

  {

    this.name = x$1;

  }

 

  public int score() //get

  {

    return this.score;

  }

 

  public void score_$eq(int x$1) //set

  {

    this.score = x$1;

  }

 

  public Person(int age, String name, int sex, int score1)

  {

    this.score = score1;

    Predef..MODULE$.print("Ö÷¹¹ÔìÆ÷");

  }

 

  public static void main(String[] paramarrayofstring)

  {

    Person..MODULE$.main(paramarrayofstring);

  }

}

从上面的代码和结果可以得:

1、主构造器的声明直接放在类名后面

2、主构造器会执行所有的代码方法定义除外

3、如果主构造无参数,后面的小括号可以省略(简单,不作证明)

4、如果想让主构造器私有化,则可以在(参数)前面添加private关键字

5、从上面代码中我们在Person类中有三个变量

被val修饰,则为只读属性,会生成一个相当于get的方法(反编译看)

被var修饰,则为读写属性,会生成一个相当于get和set的方法

没有被修饰,则是一个局部变量,则不会生成任何方法

其中的sex属性没有生产任何的方法,是局部变量,而score是里面定义的变量,朱构造器也会执行,score1是局部变量,也不会生成任何的相关方法

3、辅助构造器

class Person(val age:Int,var name:String, sex:Int, score1:Int) {
  var score = score1
  println("主构造器")

  def this(age:Int, name:String){
    //辅助构造器必须显示调用主构造器,可以通过调用其他辅助构造器间接调用
    this(age,name,21,99)
    print("辅助构造器")
  }
}

object Person{
  def main(args: Array[String]): Unit = {
    new Person(3,"zhangsan")
  }
}

 

运行结果:

 

 

辅助构造器的名称为this,多个辅助构造器通过不同的参数列表进行区分,也就是重载

4、Bean属性

       将scala字段添加@BeanProperty就会生成java类似的get和set方法

import scala.beans.BeanProperty

class Person( val name:String, @BeanProperty var age:Int) {
  print("主构造器")
}

object Person{
  def main(args: Array[String]): Unit = {
    new Person("zhangsan",7)
  }
}

 

反编译结果

public class Person

{

  private final String name;

 

  public String name()

  {

    return this.name;

  }

 

  public int age()

  {

    return this.age;

  }

 

  public void age_$eq(int x$1)

  {

    this.age = x$1;

  }

 

  public void setAge(int x$1)  //setAge

  {

    this.age = x$1;

  }

 

  public int getAge() //getAge

  {

    return age();

  }

 

  public Person(String name, int age)

  {

    Predef..MODULE$.print("主构造器");

  }

 

  public static void main(String[] paramarrayofstring)

  {

    Person..MODULE$.main(paramarrayofstring);

  }

}

从上面的代码,可以得出生成了get和set方法,如果是val修饰,则只会有get方法

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐