Scala Classes and Objects
Class Introduction
Introduction
A class is the blueprint for an object. Once you have defined a class, you can create objects from the class's blueprint using the keyword new. In the definition of a class, you can place fields and methods, which are generally referred to as members. For a field, whether Val or var is defined, it is a variable that points to the object. For methods, defined with Def, contains the executable code. A field retains the state or data of an object, and the method uses that data to perform the operation of the object. When a class is instantiated, the runtime environment reserves some memory to preserve the object's state image-that is, the contents of the variable.
Example
To create a class example:
Class Sumaccumulator { var sum = 0}
Then instantiate two times:
Val acc:sumaccumulator = new Sumaccumulatorval csa:sumaccumulator = new Sumaccumulator
At this point the state image of the object in memory is as follows:
Because the field sum is a var type and not a Val, sum can be given a new value of type int: for example
Acc.sum = 3
At this point the image will become:
Important features of the Scala class
access Modifiers
- Public is the default access level for Scala
To ensure the robustness of the object, you can make the field in the class private (private) to prevent it from being accessed directly by the outside world. Because a private field can only be defined as a method access within the same class, all code that is followed by the new field is locked into the class. To declare a field to be private, you can place the access modifier private on the front of the field.
code example:
Class Sumaccumulator { private var sum = 0}
Any access to sum from outside the class will fail when the private adornment is used
Val acc:sumaccumulator = new Sumaccumulatoracc.sum = 3 //compilation does not pass because sum is private
Method
1. Scala method parameter types
The types in Scala method parameters are Val rather than var type
def add (A:int, b:int): Int = { A = a + b //Compile error: Reassignment to Val (that is, error assigned to Val type) a}
2. return in Scala method
The return in the Scala method can be removed to simplify the code
code example:
def numsum (num:int): Int ={ val sum = num + ten sum //Omit return keyword, simplify code}
At this point the return value is sum
3. The "=" Sign in the Scala method
The "=" sign in the Scala method is very important: because the Scala compiler can convert any type to unit, if the defined function "=" is forgotten to add, then Scala defaults to its return value as the unit type. If you want to return a string of type value, the string type return value is cast to the unit type and discarded because no "=" is added.
code example:
Def printstr () { "This is the return value of string type}"
The returned result is: ()
Correct code example:
Def printstr (): string = { "This is the return value of string type"}
The returned result is: This is the return value of type string
4. Scala method Expressions
If a method only evaluates an expression of a single result, this can remove the curly braces, and if the result expression is short, it can even be placed on the same line of def.
code example:
def numsum (num:int): Int = num + 10
5. the semicolon inference in Scala
In a Scala program, a semicolon at the end of a statement is usually optional, and without a semicolon, if there is only one statement on a line. However, if a row contains multiple statements, the semicolon is required.
Do not add semicolons:
if (x < 2) println ("too small") Else println ("OK")
You must add a semicolon:
val x = 10; println (x) //Two statements, you must add a semicolon
The usual style of Scala is to put the operator at the end of the line instead of the outfit:
Error Example:
Val x = 10;val y = 3val z = x//It will be recognized by the compiler as Z = x; +y of two statements +y
Printing results:
10
Correct example:
Val x = 10;val y = 3val z = x + yprintln (z)
Printing results:
13
Scala semicolon inference rules:
- A question line ends with a word that cannot be lawfully terminated as a statement, such as a period or infix operator.
- The next line begins with a word that cannot be started as a statement.
- Line ends in parentheses (...) or box [...] Internally, because these symbols cannot hold more than one statement.
6. Scala's no-reference method
When calling the Scala class without a parameter method, you can either write the parentheses or do not write. For the accessor in the class, it is a good style to remove ().
code example:
Object EXAM1 { def main (args:array[string]): Unit = { val per:person = new person per.talk () //ok PE R.talk //same OK }}class person { def talk (): Unit = println ("Talking")}
If you want to enforce this style, you can declare the method without ()
code example:
Per.talk ()//This is the wrong type of Per.talk//ok class Person { def talk = println ("Talking")}
getter and setter in Scala class
Getter and setter
If you use a public field in a Scala class, anyone can modify the field to make it much less secure. So we're more inclined to use getter and setter methods:
Scala provides getter and setter methods for each field in the class, called Age and age_=, respectively.
code example:
Val Per:person = new Personper.age = 18class person { var = 0}
If you want to see these methods, you can first compile the person class and then use JAVAP to view the bytecode:
You can redefine getter and setter methods yourself
code example:
Object EXAM1 { def main (args:array[string]): Unit = { val per:person = new person per.age = Per.age = / /due to the control of age within the setter is not small, so the result of age does not change println (per.age) per.age = + //use setter, give greater than the original age println (per.age) }}class person { private var privateage = 0 //change to private variable and rename def age = Privateage def age_= (newage:int) { ///age_= cannot have spaces if (NewAge > Privateage) privateage = newage //Make age not smaller }}
Printing results are:
1819
Each field in Scala generates a getter and setter limit:
- If the field is private, the getter and setter methods are also private.
- If the field is Val, only the getter method is generated.
- If you don't need any getter or setter, you can declare the field as Private[this]
Scala's four choices when implementing attributes in a class:
- Automatically generates a getter and setter.
- Automatically generates a getter.
- Customize the Foo and foo_= methods.
- Customize the Foo method.
BeanProperties
The JavaBean specification defines Java properties as a heap of Getfoo and Setfoo methods. Similar to Java, Getter and setter methods are automatically generated when you label the Scala field as @BeanProperty.
code example:
Import Scala.beans.BeanPropertyobject exam1 { def main (args:array[string]): Unit = { val per:person = new person per.name = "Zhagnsan" per.setname ("Lisi") //beanproperty generated SetName method println (per.getname) / /beanproperty generated GetName method }}class Person { @BeanProperty var name:string = _}
Printing results are:
Lisi
There are four methods generated by @beanproperty in the above class person:
1. Name:string2. Name_= (newvalue:string): Unit3. GetName (): String4. SetName (newvalue:string): Unit
The diagram shows the method generated for the field:
Scala class in constructors
Like Java or C + +, Scala can have any number of constructors. However, the Scala class has a constructor that is more important than any other constructor, which is the main constructor. In addition to the main constructor, the Scala class can have any number of auxiliary constructors.
Auxiliary Constructors
The auxiliary constructors in Scala are very similar to Java or C + +, with only two distinct differences:
- The name of the secondary constructor is this.
- Each secondary constructor must start with a call to a different auxiliary constructor or main constructor that was previously defined
Here is a class with two auxiliary constructors.
code example:
Object EXAM1 { def main (args:array[string]): Unit = { val per1:person = new person //main constructor Val per2:pers on = new Man ("Bob") //First Auxiliary constructor val Per3:person = new Person ("Bob", +)//second auxiliary constructor }}class-
private var name = "" private var age = 0// an auxiliary constructor def this (name:string) {This ( )//Call main constructor Thi S.name = name } //Another auxiliary constructor def this (name:string, age:int) {This (name)//Call the previous auxiliary constructor This.age = Age }}
Main constructor
In Scala, each class has a primary constructor. The main constructor is not defined by the This method, but is intertwined with the class definition.
The parameters of the main constructor are placed directly after the class name
code example:
Object EXAM1 { def main (args:array[string]): Unit = { val per:person = new Person ("Bob", 18)//instantiation of object with main constructor p Rintln (Per.name + ":" + per.age) }}class person (Val name:string, Val age:int) { //Generate private name and age, no setter / /.....}
Printing results:
Bob:18
The short person class definitions above greatly simplify the Java code for the same functionality:
Example Java code with the same functionality as the previous example:
Class Person { private String name; private int age; Public person (String name, Int. age) { this.name = name; This.age = age; } Public String name () { return this.name; } public int Age () { return this.age; }}
All the statements defined by the Scala main constructor will execute
code example:
Class Person (Val name:string, Val age:int) { //generates a private name and age, without setter println ("All statements defined by the main constructor will execute") // def description = name + ' is ' + age + ' years old ' will be executed every time the main constructor is used
The different types of main constructor parameters correspond to the fields and methods that will be generated:
If you want to make the main constructor private, you can place the private keyword like this:
Class Person Private (Val name:string, Val age:int) { //...}
In this way, the class user must construct the person object through the secondary constructor.
Scala Nested classes
In Scala, you can embed any syntactic constructs in almost any grammatical structure. You can define a function in a function to define a class in a class.
code example:
Class Network { //define classes in the network class Member Member (val name:string) { val contacts = new Arraybuffer[member ] } private val members = new Arraybuffer[member] def join (name:string) = { val m = new Member (name) Members + = m }}
Consider the following two networks:
Val chatter = new Networkval Myface = new Network
In Scala, each instance has its own member class, just as they have their own members field. That means chatter. Member and Myface.member are different two classes.
Role: With the network example, you can add members to your own network, but you can't add members across the Web.
code example:
Val chatter = new Networkval myface = new Networkval fred = Chatter.join ("Fred") Val Wilma = Chatter.join ("Wilma") Fred.cont Acts + = Wilma //okval Barney = Myface.join ("Barney")//Error: Cannot add a myface.member to the Chatter.member element buffer Fred.contacts + = Barney
In a nested class, you can access this reference to the external class through the external class. this, just like in Java.
Class Network (Val name:string) { //in the Network class, define classes Member Member (val name:string) {// .... def description = name + "Inside" + Network.this.name }}
If you feel the need, you can also use the following syntax to establish an alias to the reference:
Class Network (val name:string) {outer =/ ////In the Network class Member classes Member (Val name:string) { //....< C10/>def Description = name + "Inside" + Outer.name }}
The syntax above makes the outer variable point to network.this. For this variable, you can use any valid name.
Scala Classes and objects