Classes (Class)
A class is a template for an object that, by constructing a class, can declare a series of objects of the same structure using the New keyword.
One source file for Scala can contain more than one public class.
Declaring the person class:
Class person{
var name:string = _
Val Age = 10
Private[this] val gender = "Male"
}
Description
The Name field is assigned the value "_" "_", which is a placeholder. Indicates that name is declared as String. But the assignment is "_", that is, the actual value is temporarily not assigned.
If you use a placeholder, Scala cannot determine the type of name, so you must declare the type of the field.
Gender is limited to "private[this" in person and cannot be called outside of the class.
Scala Builder
The Scala constructor differs greatly from the Java constructor. The constructors in Scala are divided into the primary constructor and the secondary constructor.
Main constructor
Each class in Scala has a primary constructor and is interwoven with the class definition.
The parameters of the Scala main constructor are placed directly after the class name.
If a class does not explicitly define a primary constructor, it automatically has an parameterless main constructor.
Example: the declaration of the main constructor.
Class Person (Val name:string, var age:int) {
// ...
}
Statements that are not placed in the method body in the Scala class are executed.
Example: The method body of the main constructor.
Class Person (Val name:string, var age:int) {
println ("This is primary constrator!")
}
The parameters of the main constructor are compiled into fields, and the incoming is initialized when the object is constructed.
Cases:
Object personmain{
def main (args:array[string]) {
Val p = new Person ("Tom", 18);
println ("P is" + P.name + "," + p.age)
}
}
Output:
Cases:
Class Person (Val name:string, var age:int) {
println ("person is created")
Val id = name + ":" + Age
}
Val p = new Person ("Tom", 18)
Description
The person class has three field name,age,id.
The parameters of the main constructor are generally four kinds:
Value:string
An immutable private field for an object that does not have a method using value in the object, there is no field. That is equivalent to Private[this] Val.
Private Val value:string or private var value:string
The private field of the object, the private Getter/setter method.
Val/var value:string
The private field of the object, the public Getter/setter method.
@BeanProperty Val/var value:string
Private fields, common Scala and JavaBean getter/setter methods
Private Main constructor
Class HelloWorld Private (main constructor) {type member}
The main constructor is private and can only be constructed from the secondary constructor.
Sub-constructors (auxiliary constructors)
The Scala class can have any number of secondary constructors.
Scala's sub-constructors are defined in the class with a name of "this".
Cases:
Class Person (Var name:string, Val age:int) {
println ("This is primary constrator!")
var gender:string = _
def this (name:string, Age:int, gender:string) {
This (name, age)
This.gender = Gender
}
}
Output:
The primary constructor must be called in the secondary constructor, or the other secondary constructors must be called, and the main constructor has to be called in the other secondary constructors. That is, all the secondary constructors must have one call to the main constructor.
Recorded:
Class helloworld{
private var value1 = ""
private var value2 = ""
def this (m:string) {
This ()//Call main constructor
This.value1=m
}
def this (m:string,n:string) {
This (m)//call the defined secondary constructor
This.value2=n
}
}
Analysis: Constructors and functions
The parameters of the main constructor are allowed with the Val/var keyword, and the parameters of the function cannot be accompanied by these keywords.
The parameters of the main constructor are allowed with the Val/var keyword, and the parameters of the secondary constructor cannot be accompanied by these keywords.
Scala Object
There is no concept of static in Scala. But Scala uses object to provide similar functionality.
Single-instance objects
The object syntax defines a single instance of the class.
Object accounts{
private var lastnum = 0
def newuniquenum = {
Lastnum + = 1
Lastnum
}
}
The method in object, which can be treated as a static method.
Call the method in object, call it directly, without new.
Accounts.newuniquenum ()
The constructor of the object is called when the object is used for the first time.
The object syntax structure is roughly the same as class, except that object cannot provide constructor parameters.
An environment that typically uses singleton objects:
As a place to store tool functions or constants.
Share a single immutable instance.
Orchestrate a service with a single instance.
Associated objects
There are classes in Java that have both an instance method and a static method. The same thing can be achieved in Scala through the associated objects of classes and classes.
When a singleton object has the same name as a class, it is called a companion object.
Class account{...} Associated class
Object account{...} Associated objects
Classes and their associated objects can access private properties, but must exist in the same source file.
The associated object of a class can be accessed, but not in scope.
Cases:
Class account{...}
Object account{def newuniquenum = {...}}
The HelloWorld class must call the Newuniquenum () method in the companion object through Account.newuniquenum (), and not directly with Newuniquenum ().
The associated object is also a way to extend the functionality of the class. Because the associated class can directly use the method of the associated object.
Apply method
The Apply method is designed to simplify the method of creating class instances. The Apply method is similar to the factory method. When you need to construct a companion object with parameter requirements, you will typically define and use the object's apply method. The Apply method returns the object of the associated class.
The Apply method is called when an expression of the following form is encountered: Object (parameter 1, ..., parameter n)
Example: The graph object in Spark source code.
The Graphimpl method is also an object.
Example: The array object defines the Apply method, and you can create arrays with the following expressions:
Array ("Mary", "had", "a", "little", "lamb")
Analysis:
Arrays (100) return an array of 1 elements. The element value is 100.
The new Array (100) returns an array of 100 elements. The value of each element is null.
Cases:
Class applyoperation{}
Class applytest{
def havetry{
println ("A Try on apply!")
}
}
Object applytest{
def apply () = new Applytest
}
Object Applyoperation extends App {
Val A = Applytest ()
A.havetry
}
Cases:
Class HelloWorld (Var M:string,n:char) {...}
Object helloworld{
def apply (N:char) =new HelloWorld ("", N)
}
Val Hi=helloworld (' J ')
Cases:
Class Account Private (Val id:int,initialbalance:double) {
private var balance = Initialbalance
}
Object account{
def apply (initialbalance:double) = new Account (Newuniquenum, initialbalance)
}
Construct the Account object:
Val Acct = Account (1000.0)
Use the Apply method in class
The Apply method is generally used only with object. Class can also be used, but not commonly used.
Cases:
Class applyoperation{}
Class applytest{
def apply () = "Apply in class"
def havetry{
println ("A Try on apply!")
}
}
Object applytest{
def apply () = new Applytest
}
Object Applyoperation extends App {
Val A = new applytest
Val applystr = A ();
println (APPLYSTR)
}
Output:
Scala inheritance
Inheritance is the extension of classes.
Extends is a reserved word that implements inheritance in Scala:
Class Week extends month{...}
Description
The week class inherits all non-private members of the month class.
The week class is a subclass of the month class, and the month class is a superclass of the week class.
Subclasses can override members of a superclass (with the same name and parameters).
Cases:
Class Student (Name:string, Age:int, Val major:string) extends person (name, age) {
println ("This was subclass of person, Major is:" + major)
}
A singleton object can also inherit from a class, the same as the inheritance syntax of a class:
Object Day extends week{...}
Can a singleton object be inherited?
Rewrite
Use override reserved word for method, field rewrite in Scala
Class Week extends month{
Override Def FirstDay = {...}
}
The override reserved word is actually used similar to private, the definition after declaring this reserved word is a rewrite of the superclass, so it can also be written in the parameters of the class definition
Class Week (override Val lastday:string) extends month{...}
A subclass that overrides or modifies Scala examines its superclass, but the superclass's modifications do not check its subclasses
Cases:
Class Student (Name:string, Age:int, Val major:string) extends person (name, age) {
println ("This was subclass of person, Major is:" + major)
Override Def tosting = "Override Tosting"
}
Overrides include fields and methods, but methods with different parameters can not be overridden
Class month{def secondday (m:string) ={...}}
Class Week extends month{def secondday ={...}
Rules:
Rewrite def
With Val: use Val to rewrite superclass with no parameter method (getter)
Use Def: Subclass method and Superclass method duplicate name
Use Var: simultaneously rewrite getter, setter method, only rewrite Getter method error
Rewrite Val
With Val: A private field of a subclass that has the same name as a superclass field, the Getter method overrides the superclass's Getter method
Rewrite var
var: And when the superclass's Var is abstract to be rewritten, the Var of the superclass will be inherited.
Cases:
Class month{
Val one = 25//Can be overridden in subclasses with Val
var = 15//cannot be overridden with Var in subclasses because it is not abstract
var three:int
def firstday =//Can be overridden in subclasses with Val
def now =//can be overridden in subclasses with Var
def now_ =
def lastday (M:char) ={}//Can be overridden in subclasses with Def
}
Summarize:
Subclasses, Def can only override the superclass of the def,val can rewrite the superclass of Val or Def,var without parameters can only override the superclass in the abstract var or superclass Getter/setter pair.
Anonymous sub-class
Val alien = new Person ("Fred") {
def greeting = "Greetings, earthling! My name is Fred "
}
Scala Basics: Object-oriented-class