Scala -- definition of classes and objects + use of associated objects

Keywords: Scala Big Data Hadoop

1. Classes and objects

Scala is a functional object-oriented language. It also supports the idea of object-oriented programming, and also has the concept of class and object. We can still develop object-oriented applications based on Scala.

1.1 related concepts

What is object oriented?

Object oriented is a programming idea, It is based on process oriented, The emphasis is to complete various operations based on objects.

What are the three characteristics of object-oriented thought?

1. More in line with people's thinking habits.
2. Simplify complex things.
3. Change programmers from executors to commanders.

Interview question: what is object oriented? Idea: overview, characteristics, examples and summary

What is a class?

A class is a collection of properties and behaviors, Is an abstract concept, unseen, I can't touch it.
  • Attribute (also known as member variable): noun used to describe the external characteristics of things

  • Action (also known as member method): verb indicating what things can do

  • For example, students have names and ages (these are attributes), students have to study and eat (these are behaviors)

What is an object?

Object is the concrete embodiment of class, realization. 

What are the three characteristics of object-oriented?

encapsulation, inherit, polymorphic.

1.2 creating classes and objects

Creating classes and objects in Scala can be realized through the class and new keywords. Create classes with class and objects with new

1.2.1 example

Create a Person class, create its object, and print the object to the console

1.2.2 steps
  1. Create a scala project and an object class

    Note: the class modified by object is a singleton object, which can be understood first and will be explained in detail later

  2. Add the main method to the object class

  3. Create the Person class, create the object of the Person class in the main method, and then output the result

  • Add the main method in the object class and complete the specified code as required
//Case: test how to create classes and objects in Scala programs
object ClassDemo01 {

  //1. Create Person class
  class Person {}

  //2. Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Create an object of type Person
    val p = new Person()
    //4. Print the object to the console
    println(p)
  }
}

1.3 abbreviation

usage

  • If the class is empty and has no members, {} can be omitted
  • If the constructor parameter is null, you can omit ()

Example

Recreate the Person class and object using shorthand, and print the object

Reference code

//Case: creating classes and objects in Scala through shorthand
object ClassDemo02 {

  //1. Create Person class
  class Person 

  //2. Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Create an object of type Person
    val p = new Person
    //4. Print the object to the console
    println(p)
  }
}

2. Define and access member variables

A class will have its own attributes. For example, human beings have their own name and age. Let's next learn how to define and access member variables in a class.

2.1 usage

  • Use var/val in the class to define member variables
  • Object can access member variables by object name

2.2 example

demand

  1. Define a Person class that contains a name and age field
  2. Create a 23-year-old object named "Zhang San"
  3. Print the name and age of the object

step

  1. Create an object class and add the main method
  2. Create the Person class, add the name field and age field, initialize the field, and let scala automatically infer the type
  3. Create a Person class object in the main method and set the member variables to "Zhang San" and "23"
  4. Print the name and age of the object

Reference code

//Case: defining and accessing member variables
object ClassDemo03 {

  //1. Create Person class
  class Person {
    //2. Define member variables
    //val name:String = ""
    //Implemented by type inference
    //The value of var modified variable can be modified. The value of val modified variable cannot be modified
    var name = ""   //full name
    var age = 0     //Age
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Create an object of type Person
    val p = new Person
    //4. Assign values to member variables
    p.name = "Zhang San"
    p.age = 23
    //5. Print the member variable value to the console
    println(p.name, p.age)
  }
}

3. Initialize member variables with underscores

scala has a more concise way to initialize member variables, which can make the code look more concise and elegant

3.1 usage

  • When defining member variables of var type, you can use_ To initialize member variables
    • String => null
    • Int => 0
    • Boolean => false
    • Double => 0.0
    • ...
  • Member variables of type val must be initialized manually

3.2 example

demand

  1. Define a Person class that contains a name and age field
  2. Create a 23-year-old object named "Zhang San"
  3. Print the name and age of the object

step

  1. Create an object class and add the main method
  2. Create the Person class, add the name field and age field, specify the data type, and initialize with underscores
  3. Create a Person class object in the main method and set the member variables to "Zhang San" and "23"
  4. Print the name and age of the object

Reference code

//Case: initializing member variable values with underscores
//Note: this method is only valid for variables of var type. If it is a variable of val type, it needs to be assigned manually
object ClassDemo04 {

  //1. Create Person class
  class Person {
    //2. Define member variables
    var name:String = _   //full name
    var age:Int = _       //Age
    //val age:Int = _     // This will report an error, because the "underline assignment" method is only valid for var modified variables
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Create an object of type Person
    val p = new Person
    //4. Assign values to member variables
    p.name = "Zhang San"
    p.age = 23
    //5. Print the member variable value to the console
    println(p.name, p.age)
  }
}

4. Define and access member methods

Classes can have their own behavior, and scala can define the behavior of classes by defining member methods.

4.1 format

In scala classes, def is also used to define member methods

def Method name(Parameter 1:data type, Parameter 2:data type): [return type] = {
    //Method body
}

Note: the type of the return value can not be written, and Scala automatically infers the type

4.2 example

demand

  1. Create a Customer class

  2. Create an object of this class and call the printHello method

step

  1. Create an object class and add the main method
  2. Create a Customer class and add member variables and member methods
  3. Create a Customer class object in the main method and set the value of the member variable (Zhang San, male)
  4. Call member method

Reference code

//Case: defining and accessing member methods
object ClassDemo05 {

  //1. Create Customer class
  class Customer {
    //2. Define member variables
    var name:String = _   //full name
    var sex = ""          //Gender

    //3. Define member method printHello
    def printHello(msg:String) = {
      println(msg)
    }
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //4. Create an object of Customer type
    val c = new Customer
    //5. Assign values to member variables
    c.name = "Zhang San"
    c.sex = "male"
    //6. Print the member variable value to the console
    println(c.name, c.sex)
    //7. Call member method
    printHello("Hello!")
  }
}

5. Access modifier

Like Java, scala can also control whether member variables and member methods can be accessed by the outside world through access modifiers.

5.1 definitions

  1. Access control in Java is also applicable to scala. You can add private/protected keywords in front of members to control the visibility of members.

  2. In scala, there is no public keyword, and any member that is not marked private or protected is public

    be careful:
    In Scala, there are only four permission modifiers: private, private[this], protected, which are the default

5.2 cases

demand

  • Define a Person class

  • Create an object of this class in the main method to test whether private members can be accessed

Reference code

//Case: demonstrate the access modifier in Scala
/*
  be careful:
    1. Scala private/protected can be used to decorate members in
    2. If the member is not modified by private/protected, it is public by default (similar to public in Java)
 */
object ClassDemo06 {

  //1. Create Customer class
  class Customer {
    //2. Define member variables and privatize them all
    private var name = "" //full name
    private var age = 0 //Age

    //3. Define member methods
    //Get name
    def getName() = name

    //Set name
    def setName(name: String) = this.name = name

    //Get age
    def getAge() = age

    //Set age
    def setAge(age: Int) = this.age = age

    //Greeting method, which needs to be privatized
    private def sayHello() = println("Hello, Scala!")
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //4. Create an object of Customer type
    val c = new Customer
    //5. Assign values to member variables
    //c.name = "Zhang San" / / an error will be reported if it is written like this, because private members cannot be accessed directly by the outside world
    c.setName("Zhang San")
    c.setAge(23)
    //6. Print the member variable value to the console
    println(c.getName(), c.getAge())
    //7. Try calling the private member method
    //c.sayHello() / / an error will be reported if it is written like this, because private members cannot be accessed directly by the outside world
  }
}

6. Class constructor

When an object is created, the constructor of the class is automatically called. The default constructor was used before. Next, we will learn how to customize the constructor.

6.1 classification

  • primary constructor
  • Auxiliary constructor

6.2 main constructor

grammar

class Class name(var/val Parameter name:type = Default value, var/val Parameter name:type = Default value){
    //Construct code block
}

be careful:

  • The parameter list of the main constructor is defined directly after the class name, and val/var is added to indicate that member variables are defined directly through the main constructor
  • The constructor parameter list can specify default values
  • Create an instance and call the constructor to specify fields for initialization
  • The code in the whole class is construction code except for field definition and method definition

Example

  1. Define a Person class, define the name and age fields through the main constructor parameter list, and set their default values to Zhang San, 23
  2. Output "call main constructor" in the main constructor
  3. Create a "Li Si" object (name Li Si, age 24) and print the name and age of the object
  4. Create an "empty" object without passing any parameters to the constructor, and print the name and age of the object
  5. Create a "test" object, do not pass in the name parameter, only specify the age of 30, and print the name and age of the object

Reference code

//Case: demonstrate the main constructor of classes in Scala
/*
  be careful:
    1. Scala The parameter list of the main constructor in is written directly after the class name
    2. The parameter list of the main constructor can have default values
    3. When calling the main constructor to create an object, you can specify parameter assignment
    4. The whole class is called construction code except for the code that defines member variables and member methods
 */
object ClassDemo07 {

  //1. Create the person class. The main constructor parameter list is: name and age
  class Person(val name: String = "Zhang San", val age: Int = 23) { //var should be used here
    //2. Output "call main constructor" in the main constructor
    println("Calling the main constructor!...")
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Create an "empty" object and pass nothing
    val p1 = new Person()
    println(s"p1: ${p1.name}...${p1.age}")

    //4. Create the "Li Si" object and pass in the name and age
    val p2 = new Person("Li Si", 24)
    println(s"p2: ${p2.name}...${p2.age}")

    //5. Create a test object and only import age
    val p3 = new Person(age = 30)
    println(s"p3: ${p3.name}...${p3.age}")
  }
}

6.2 auxiliary constructor

In scala, in addition to defining the main constructor, you can also define the auxiliary constructor as needed. For example, it is allowed to create objects in a variety of ways. At this time, more constructors can be defined. We call constructors other than the main constructor auxiliary constructors.

grammar

  • Defining auxiliary constructors, like defining methods, also uses the def keyword
  • The default name of auxiliary constructors is this and cannot be modified
def this(Parameter name:type, Parameter name:type) {
    // The first line needs to call the main constructor or another constructor
    // Constructor code
}

Note: the first line of code of the auxiliary constructor must call the main constructor or other auxiliary constructors

Example

demand

  • Define a Customer class that contains a name and address field
  • Define the main constructor of the Customer class (initialization name and address)
  • Defines the auxiliary constructor of the Customer class, which receives an array parameter and uses the array parameter to initialize the member variable
  • Use the auxiliary constructor of the Customer class to create a "Zhang San" object
    • Name is Zhang San
    • The address is Beijing
  • Name and address of printing object

be careful:

  1. The case involves"array"Relevant knowledge points, We haven't learned yet.
  2. Scala Arrays and in Java The array usage in is basically similar, You can understand it now, Detailed explanations will be given in the follow-up meeting. 

Reference code

//Case: demonstrate the auxiliary constructor of classes in Scala
object ClassDemo08 {

  //1. Create a Customer class. The main constructor parameter list is: name and address
  class Customer(var name: String, var address: String) { //var should be used here
    //2. Define an auxiliary constructor to receive an array parameter
    def this(arr:Array[String]) {
      this(arr(0), arr(1))    //Pass the first two elements of the array to the two parameters of the main constructor
    }
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Call the auxiliary constructor to create the Customer object
    val c = new Customer(Array("Zhang San", "Beijing"))
    //4. Print results
    println(c.name, c.address)
  }
}

7. Singleton object

There is no static keyword in scala. If you want to define static variables and static methods similar to those in Java, you need to use the singleton object in Scala, that is, object

7.1 defining singleton objects

A singleton object means that there is only one object in the world, which is also called an isolated object. Defining a singleton object is very similar to defining a class, that is, replacing class with object

format

object Singleton object name{ }			//Define a singleton object

be careful:

1. stay object The member variables defined in are similar to Java Static variables in, There is only one object in memory.

2. In singleton objects, Can be used directly`Singleton object name.`Calling members as.

Example

demand

  • Define a Dog singleton object and save how many legs the Dog has
  • Print the number of dog legs in the main method

Reference code

//Case: demonstrate the definition of singleton object and accessing member variables in Scala
object ClassDemo09 {

  //1. Define the singleton object Dog
  object Dog {
    //2. Define a variable to store the number of doglegs
    val leg_num = 4
  }

  //Define the main method, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Print the number of doglegs
    println(Dog.leg_num)
  }
}

7.2 defining methods in singleton objects

Member methods defined in singleton objects are similar to static methods in Java

Example

demand

  • Design a singleton object and define a method that can print split lines (15 minus signs)
  • Call this method in the main method to print the split line

Reference code

//Case: demonstrate the definition of singleton object and member access method in Scala
object ClassDemo10 {

  //1. Define the singleton object PrintUtil
  object PrintUtil {
    //2. Define a method to print split lines
    def printSpliter() = println("-" * 15)
  }

  //Define the main method, which is the main entry of the program
  def main(args: Array[String]): Unit = {
    //3. Call the member method in the singleton object
    PrintUtil.printSpliter()
  }
}

8. main method

scala, like Java, must have a main method to run a program. In Java, the main method is static, while in scala, there is no static method. So in scala, the main method must be placed in a singleton object.

8.1 define main method

main method

def main(args:Array[String]):Unit = {
    // Method body
}

Example

demand

  • Create a singleton object and print "hello, scala" in the singleton object

Reference code

object Main5 {
  def main(args:Array[String]) = {
    println("hello, scala")
  }
}

8.2 inheritance

Create an object, inherit from the App trait, and then write the code that needs to be written in the main method in the object constructor.

object Singleton object name extends App {
    // Method body
}

Example

demand

  • Inherit App characteristics to implement an entry. Also output "hello, scala"

Reference code

object Main5 extends App {
  println("hello, scala")
}

9. Associated objects

In Java, there are often some classes with both instance members and static members. For example:

public class Generals {

    private static String armsName = "falchion";

    public void toWar() {
        //to war
        System.out.println("General, take it"+ armsName +", go to the front to fight the enemy!");
    }

    public static void main(String[] args) {
        new Generals().toWar();
    }
}

In scala, to achieve a similar effect, you can use companion objects.

9.1 defining associated objects

A class and object have the same name. This object is called an associated object, and this class is called an associated class

  • The associated object must have the same name as the associated class
  • Associated objects and associated classes are in the same scala source file
  • Associated objects and associated classes can access private properties from each other

Example

demand

  • Write a general class with a toWar method to print

    General, take it**arms, go to the front to fight the enemy!		//Note: * * indicates the name of the weapon
    
  • Write a general companion object and define a private variable to save the weapon name

  • Create a general object and call the toWar method

Reference code

//Case: demonstrating companion objects in Scala
object ClassDemo12 {

  //1. Define a class, general, as an associated class
  class Generals {    //All written here are non - static members
    //2. Define a toWar() method and output a sentence in the format of "generals take * * weapons and go to battle to kill the enemy!"
    def toWar() = println(s"General, take it ${Generals.armsName}arms, go to the front to fight the enemy!")
  }

  //3. Define a companion object to save "generals' weapons"
  object Generals {   //All written here are static members
    private var armsName = "falchion"
  }

  //Define the main method as the main entry of the program
  def main(args: Array[String]): Unit = {
    //4. Create an object of the general class
    val g = new Generals
    //5. Call the toWar method in the general class
    g.toWar()
  }
}

9.2 private[this] access rights

If the permission of a member is set to private[this], it means that it can only be accessed in the current class. Accompanying objects are also inaccessible

Example

Example description

  • Define a Person class that contains a name field decorated with private[this]
  • Define the associated object of the Person class and the printPerson method
  • Test whether the associated object can access members with private[this] permission

Sample code

//Case: test the access rights of private[this]
object ClassDemo13 {

  //1. Define a Person class with the attribute: name
  class Person(private[this] var name: String)

  //2. Define the companion object of Person class
  object Person {
    //3. Define a method printPerson to print the Person#name attribute value
    def printPerson(p:Person) = println(p.name)
  }

  //Define the main function, which is the main entry of the program
  def main(args: Array[String]) = {
    //4. Create an object of type Person
    val p = new Person("Zhang San")
    //5. Call the printPerson method in the Person companion object
    Person.printPerson(p)
  }
}

Note: the above code will compile and report an error. But remove [this] and you can access it

9.3 apply method

In Scala, new action is not required when creating objects. This writing method is very simple and elegant. To avoid new, we need to implement it through the apply method of the associated object.

9.3.1 format

Defines the format of the apply method

object Associated object name {
	def apply(Parameter name:Parameter type, Parameter name:Parameter type...) = new class(...)
}

create object

val Object name = Associated object name(Parameter 1, Parameter 2...)

For example: val p = Person("Zhang San", 23)

9.3.2 example

demand

  • Define a Person class that contains two fields: name and age
  • Define the apply method in the associated object to realize the new free operation of creating Person object
  • Create the object of this class in the main method and print the name and age

Reference code

//Case: demonstrate the apply method in Scala
object ClassDemo14 {

  //1. Define the Person class, and the attributes are name and age
  class Person(var name: String = "", var age: Int = 0)

  //2. Define the companion object of Person class
  object Person {
    //3. Define the apply method to avoid new when creating the Person object
    def apply(name:String, age:Int) = new Person(name, age)
  }

  //Define the main method as the main entry of the program
  def main(args: Array[String]): Unit = {
    //4. Create an object of type Person
    val p = Person("Zhang San", 23)
    //5. Print the attribute value of the Person object
    println(p.name, p.age)
  }
}

10. Case: defining tool classes

10.1 general

The concept of tool class in Scala is the same as that in Java

1. All construction methods are privatized, The purpose is not to let the outside world create tool class objects through construction methods.
2. All members are static, It means that the outside world can pass through"Class name."To access the content in the tool class.

To sum up, in Scala, only the object singleton object meets the above requirements

10.2 example

demand

  • Write a DateUtils tool class to format date and time
  • Define a method to convert a Date to a Date string, for example, 2030-10-05
  • Defines a method to convert the date string to date

step

  • Define a DateUtils singleton object
  • Define the date formatting method (date2String) and the string parsing method (string2Date) in DateUtils
  • Use SimpleDateFormat to realize the conversion between String and Date

Reference code

//Case: define DateUtils tool class to realize the conversion between String and Date
object ClassDemo15 {

  //1. Define the DateUtils tool class. / / that is, the singleton object in Scala
  object DateUtils {
    //2. Create an object of type SimpleDateFormat for conversion
    var sdf: SimpleDateFormat = null

    //3. Define the date2String method, which is used to convert the Date object into a Date of String type
    //Parameter 1: Date object, parameter 2: template
    def date2String(date: Date, template: String):String  = {
      sdf = new SimpleDateFormat(template)
      sdf.format(date)
    }

    //4. Define the method string2Date, which is used to convert a Date of String type into a Date object
    def string2Date(dateString: String, template: String) = {
      sdf = new SimpleDateFormat(template)
      sdf.parse(dateString)
    }
  }

  //Define the main method as the main entry of the program
  def main(args: Array[String]): Unit = {
    //5. Call DateUtils#date2String() method to format the date
    val s = DateUtils.date2String(new Date(), "yyyy-MM-dd")
    println("format date: " + s)

    //6. Call DateUtils#string2Date() method to parse date string
    val d = DateUtils.string2Date("1314 May 21", "yyyy year MM month dd day")
    println("Parse string: " + d)
  }
}

Posted by knsito on Sun, 28 Nov 2021 19:14:00 -0800