Scala main class constructor

Class's constructor
当创建类对象的时候,会自动调用类的构造器。之前使用的都是默认构造器,我们接下来要学习如何自定义构造器。
primary constructor
We learned, Java constructor, there is a list of construction and construction code blocks
java class Person { // 成员变量 private String name; private Integer age; // Java构造器 public Person(String name, Integer age) { // 初始化成员变量 this.name = name; this.age = age; } }
In the scala, we can use more concise syntax to achieve.
Syntax
scala class name of the class (var / val Parameter name: Type = default, var / val Parameter name: Type = default) {} // constructor code block
Argument list in the main constructor is defined directly after the class name added to the val / var expressed directly through the main constructor defined member variable
argument list structure may specify default values
to create an instance, call the constructor may specify the fields to initialize
the entire class of in addition to code field definitions and methods defined in the code are configured

Example
define a Person class, the main constructor parameter list defined field name and age, and set to their default values
output "primary constructor calls" main constructor
Create "John Doe" object (name of Zhang, age 20), the name and age of the print object
create "empty" object does not pass any parameter to the constructor, the name and age of the print object
create "man40" object does not pass the name parameter specifies the age of 40, a print object the name and age
reference code
scala object _06ConstructorDemo { // 定义类的主构造器 // 指定默认值 class Person(var name:String = "", var age:Int = 0) { println("调用主构造器") } def main(args: Array[String]): Unit = { // 给构造器传入参数 val zhangsan = new Person("张三", 20) println(zhangsan.name) println(zhangsan.age) println("---") // 不传入任何参数 val empty = new Person println(empty.name) println(empty.age) println("---") // 指定字段进行初始化 val man40 = new Person(age = 40) println(man40.name) println(man40.age) } }
Here Insert Picture Description
answer
Here Insert Picture Description

Published 139 original articles · won praise 333 · views 210 000 +

Guess you like

Origin blog.csdn.net/qq_45765882/article/details/104302225