Spark basic study notes: Scala classes and objects

Article Directory

one type

(1) Class definition

Objects are concrete instances of classes. Classes are abstract and do not occupy memory, while objects are concrete and occupy storage space.
insert image description here

class User {
    private var name = "张三丰"
    private var gender = "男"
    private var age = 25

    def speak(): Unit = println(name + ", " + gender + ", 今年" + age + "岁了~")
}

(2) Instantiation of the class

insert image description here
insert image description here

2. Singleton object

(1) Singleton object concept

There are no static methods or static fields in Scala, but you can use the keyword object to define a singleton object. The methods in the singleton object are equivalent to the static methods in Java, and you can directly use the "singleton object name. method name" method to call . A singleton object can have all the characteristics of a class except that it has no constructor parameters.

(2) Case demonstration

insert image description here

object Person {
    private var name = "陈燕文"
    private var gender = "女"
    private var age = 18

    def speak(): Unit = println(name + ", " + gender + ", 今年" + age + "岁了~")
}

3. Accompanying objects

(1) The concept of companion object

When a singleton object has the same name as a class, the object is called a companion object of that class. The class is called the object's companion class. A class and its companion object must be defined in the same file, and both can access their private members.

(2) Case demonstration

insert image description here

Four, get and set methods

(1) Generation principle

By default, Scala generates different get and set methods according to the modifiers of the class's properties

1. The attributes modified by val

The system automatically generates a private constant property and a public get method.

2. var modified attributes

The system will automatically generate a private variable attribute and a pair of public get/set methods.

3. Attributes modified by private var

The system will automatically generate a pair of private get/set methods, which are equivalent to the private properties of the class, and can only be used inside the class and in companion objects.

4. Attributes modified by private[this]

The system does not generate get/set methods, that is, the property can only be used inside the class.

(2) Case demonstration

Task 1. Use the get and set methods automatically generated by the system

(1) Create a Dog class

insert image description here

package net.py.obj

class Dog {
  val id: Int = 1 // 系统会自动生成公共的get方法
  var name: String = "瑞瑞" // 系统会自动生成公共的get和set方法
  private var gender: String = "公" // 系统会自动生成私有的get和set方法,只有伴生对象可以访问
  private[this] var age: Int = 5 // 系统不会生成get和set方法,即使伴生对象也无法访问
}

(2) Compile into a bytecode file

Compile Dog.scala into Dog.class, in the out directory of the project, click to open layer by layer, find Dog, that is to generate bytecode files

(3) Decompile the bytecode file into Java code

insert image description here

(4) Explain the Java code generated by decompilation

Use the name attribute as an example. In Scala, the get and set methods are not named getName and setName, but named name and name_=. Since the JVM does not allow = to appear in the method name, = is translated into KaTeX parse error : Expected group after '_' at position 97: The name() and name_̲ eq() methods corresponding to the ...method are both public; the attribute gender is modified with private var, so private modified get and set methods are generated - gender () and gender_$eq(); attribute age is modified with private[this], so no get and set methods are generated, and it can only be used inside the class.

(5) Create a singleton object to test the Dog class

insert image description here

Task 2. The user writes Scala-style get and set methods for private properties

Create the Cat class
insert image description here

Task 3. The user writes Java-style get and set methods for private properties

Create the Bird class
insert image description here

5. Constructor

(1) Main constructor

1. Constructor parameters with val or var

Create the Person class in the net.py.consrtucuor package
insert image description here

2. Constructor parameters with access rights

You can control the access rights of parameters by adding access modifiers to the parameters of the main constructor
. Create a Person class, set the parameter age as private, and set the parameter name as unmodifiable (val)

class Person (val name: String, private var age: Int) {
  
}

3. Constructor parameters without var or val

class Person (name: String, age: Int) {
  
}

Can be rewritten as a parameter with access rights

class Person (private[this] val name: String, private[this] val age: Int) {
  
}

4. Class initialization statement

Create the Dog class in the net.py.constructor package
insert image description here

package net.py.constructor

class Dog (var name: String, var age: Int){
  name = "瑞瑞"
  age = 5
  println("主构造器被调用了~")

  def speak(): Unit = println(name + "今年" + age + "岁了~")
}

// 伴生对象
object Dog {
  def main(args: Array[String]): Unit = {
    val dog = new Dog("", 0)
    dog.speak()
  }
}

Run the program to see the result

主构造器被调用了~
瑞瑞今年5岁了~

5. Privatization constructor

insert image description here

package net.py.constructor
class Cat private (var name: String, var age: Int) {
  def speak(): Unit = {
    println(name + "今年" + age + "岁了~")
  }
}

// 伴生对象
object Cat {
  def main(args: Array[String]): Unit = {
    val cat = new Cat("刘璐", 9)
    cat.speak()
  }
}

Run the program to see the result

刘璐今年9岁了~

6. No parameter constructor

Create the Bird class in the net.py.constructor package
insert image description here

package net.py.constructor

class Bird () { // 显式定义无参构造器
  var name = "mike"
  var age = 7

  def speak(): Unit = {
    println(name + "今年" + age + "岁了~")
  }
}

// 伴生对象
object Bird {
  def main(args: Array[String]): Unit = {
    val bird = new Bird() // 调用无参构造器实例化
    bird.speak()
  }
}

Run the program to see the result

mike今年7岁了~

(2) Auxiliary constructor

1. Precautions for defining auxiliary constructors

The method name of the auxiliary constructor is this
The method body of each auxiliary constructor must first call other defined constructors
The parameters of the auxiliary constructor cannot be modified with var or val

2. Case demonstration

(1) Primary constructor without parameters and auxiliary constructor with parameters

insert image description here

package net.py.constructor

class Student {
  private var name = "淑英"
  private var age = 18

  // 定义单参辅助构造器
  def this(name: String) = {
    this() // 调用无参主构造器
    this.name = name
  }

  // 定义双参辅助构造器
  def this(name:String, age: Int) = {
    this(name) // 调用单参辅助构造器
    this.age = age
  }

  // 重写toString方法
  override def toString: String = name + "今年" + age + "岁了~"
}

// 伴生对象
object Student {
  def main(args: Array[String]): Unit = {
    // 调用无参构造器实例化
    val student1 = new Student()
    println(student1)
    // 调用单参辅助构造器实例化
    val student2 = new Student("禹欢")
    println(student2)
    // 调用双参辅助构造器实例化
    val student3 = new Student("黎塘", 19)
    println(student3)
  }
}

Run the program to see the result

淑英今年18岁了~
禹欢今年18岁了~
黎塘今年19岁了~

(2) Primary constructor with parameters and auxiliary constructor with parameters

insert image description here

package net.py.constructor
class Teacher (private var name: String, private var age: Int)   { 
  private var gender = ""
  def this(name: String, age: Int, gender: String) = {
    this(name, age) // 调用双参主构造器
    this.gender = gender
  }

  // 重写toString方法
  override def toString: String = name + "," + gender + ",今年" + age + "岁了~"
}

// 伴生对象
object Teacher {
  def main(args: Array[String]): Unit = {
    // 调用三参辅助构造器实例化
    val teacher = new Teacher("萧红", 20, "女")
    println(teacher)
  }
}

Run the program to see the result

萧红,女,今年20岁~

6. Abstract class

(1) Definition of abstract class

abstract class 类名 {

}

(2) Characteristics of abstract classes

1 Abstract classes cannot be instantiated.
2 Abstract fields (non-initialized fields) and abstract methods (non-implemented methods) can be defined in an abstract class, and initialized fields and implemented methods can also be defined.

(3) Case demonstration

1. Create an abstract class - Person

Create the Person abstract class in the net.py.absclass package
insert image description here

package net.py.absclass
abstract class Person {
  var name: String // 抽象字段
  var age: Int // 抽象字段
  var address: String = "泸州市纳溪区" // 普通字段

  // 抽象方法
  def speak()

  // 普通方法
  def walk(): Unit = {
    print(name + "弹钢琴~")
  }
}

2. Inherit the abstract class and create a common class - Teacher

Create a Teacher common class in the net.py.absclass package
insert image description here`package net.py.absclass

class Teacher extends Person { // Implement abstract fields (without override) var name: String = "Xiao Hong" var age: Int = 20


// Implement abstract methods without override
def speak(): Unit = { println(name + ", this year" + age + "year-old, where I live" + address + ", good at singing and dancing." ) }

// To override the common method, you must add override
override def walk(): Unit = { println(name + "I like playing the piano~") } } `



3. Create a test singleton object - TestTeacher

Create a TestTeacher singleton object in the net.py.absclass package
insert image description here

4. Run the program and view the results

萧红,今年20岁,家住泸州市纳溪区,擅长唱歌舞蹈。
萧红喜欢弹钢琴~

7. Characteristics

(1) The concept of traits

(2) Definition of traits

1. Grammatical format

2. Case demonstration

Task 1. Create a pet trait - Pet

insert image description here

package net.py.mytrait

trait Pet {
  // 抽象字段
  var name: String
  var age: Int
  // 抽象方法
  def speak
  // 普通方法
  def eat: Unit = {
    print(name + "在吃东西~")
  }
}

Task 2. Create the running trait - Runnable

insert image description here

Task 3. Create a flying trait - Flyable

insert image description here

(3) Realization of traits

1. Grammatical format

(1) Implement a trait

class 类名 extends 特质名 {
   // 实现抽象字段
   // 实现抽象方法
}

(2) Implement multiple traits

class 类名 extends 特质名1 with 特质名2 with 特质名3 …… with 特质名n {
   // 实现抽象字段
   // 实现抽象方法
}

2. Case demonstration

Task 1. Implement a trait

package net.py.mytrait

class Cat extends Pet {
  // 实现抽象字段
  var name: String = "虎丸"
  var age: Int = 3

  // 实现抽象方法
  def speak: Unit = {
    println(name + "今年" + age + "岁了~")
  }

  // 重写普通方法
  override def eat: Unit = {
    println(name + "在吃鱼虾~")
  }
}

// 伴生对象
object Cat {
  def main(args: Array[String]): Unit = {
    // 创建猫对象
    val cat = new Cat()
    // 调用对象方法
    cat.speak
    cat.eat
  }
}

insert image description here

Task 2. Implement multiple traits

package net.py.mytrait

class Bird extends Pet with Runnable with Flyable {
  var name: String = "玲玲"
  var age: Int = 2

  def speak: Unit = {
    println("鸟儿[" + name + "]今年" + age + "岁了~")
  }

  def run: Unit = {
    println("鸟儿[" + name + "]在欢快地奔跑~")
  }

  def fly: Unit = {
    println("鸟儿[" + name + "]在自由地飞翔~")
  }
}

// 伴生对象
object Bird {
  def main(args: Array[String]): Unit = {
    // 创建鸟对象
    val bird = new Bird()
    // 调用对象方法
    bird.speak
    bird.run
    bird.fly
  }
}

insert image description here

Run the program to see the result

鸟儿[玲儿]今年2岁了~
鸟儿[玲儿]在欢快的奔跑~
鸟儿[玲儿]在自由的飞翔~

Guess you like

Origin blog.csdn.net/py20010218/article/details/125339446