Create a package named Org.scala.clazz under Scala, create a Scala class named Oopinscala.scala, and add an object Oopinscala
(The picture of the package is wrong, it should be Org.scala.clazz)
Create a user class and add the name and age fields
Invokes the user class and executes
Use of Private[this]
We can see that the gender property is inaccessible, so that the contents of the definition using Private[this] can not be used externally, so it's good to start protecting.
Constructor for the class:
The main constructor uses:
Call:
From the results of the above we can find the Scala main constructor features:
1. The main constructor follows the class name directly, and the parameters in the main constructor are compiled into the fields of the class
2. When the main constructor executes, all statements in the class that are not contained in the method body are executed
If we remove the Val in front of the name in the user main constructor, run
We can find the error message as the Name field is not a member variable of the user class
So we can find the third feature of the Scala main constructor 3, the main constructor function parameter does not use VAR or val to declare the variable, the variable at this time is private[this] level, can only be used within the class
Use of the secondary constructor:
1. The subordinate constructor is declared using this
2. The secondary constructor must call the main constructor or other subordinate constructors
The result of the call is:
Getting Started with Scala-04 classes (Class)