Scala class constructor

Main constructor

grammar:

class 类名(var/val 参数名:类型 = 默认值,...){
    
    
//构造代码块
}

Note:

  • The parameter list of the main constructor is directly defined after the class name, and val/var is added to indicate that the member variables are defined directly through the column constructor
  • The constructor parameter list can specify default values
  • Create an instance, call the constructor to specify the field to initialize
  • Except for field definitions and method definitions, the entire class is constructed code

Auxiliary constructor

grammar:

  • Defining auxiliary constructors is the same as defining methods, and also uses the def keyword to define
  • The default name of the auxiliary constructor is this and cannot be modified
def this(参数名:参数类型,...){
    
    
	//第一行需要调用主构造器或者其他构造器
	//构造器代码
}
注:辅助构造器第一行代码w必须要调用主构造器或者其他辅助构造器

Guess you like

Origin blog.csdn.net/zh2475855601/article/details/113867041