Scala learning object oriented

Keywords: Java Scala Big Data

object-oriented

  • Scala's object-oriented thought is consistent with Java's object-oriented thought and concept.
  • The syntax in Scala is different from that in Java, and more functions are added.

Scala package

  • Basic syntax: package name
  • Three functions of Scala package (same as Java)
    • Distinguish between classes with the same name
    • When there are many classes, you can manage classes well
    • Control access scope
  • Package naming:
    • Naming rules: it can only contain numbers, letters, underscores and small dots, but it can't start with numbers and don't use keywords.
    • Case operation: demo.class.exec1 / / an error occurs because of the class keyword
    • Naming convention: generally lowercase letters + small dots
  • Package description:
    • Note: Scala has two package management styles. One is the same as the package management style of Java. Each source file has a package (the package name and the path of the source file are not required to be consistent), and the package name is separated by "." to represent the hierarchical relationship of the package, such as com.atguigu.scala. Another style represents hierarchical relationships through nested styles, and this style has two characteristics:
      • Multiple package s can be declared in one source file
      • The classes in the child package can directly access the content in the parent package without importing the package

    • However, if the external package wants to access the internal package, it needs to import the package
  • Package object: in Scala, you can define a package object with the same name for each package, and define the members in the package object as its pairs
    The shared variables of all class es and object s under the package can be accessed directly.
    • Note: if the package management style of JAVA is used, the package object is generally defined in the Package.Scala file under its corresponding package, and the package object name is consistent with the package name
      • If a nested management package is used, the package object can be defined in the same file as the package, but ensure that the package object and the package declaration are in the same scope
  • Import package description: like Java, import can be used at the top, and all classes in this file can be used.
    • Local import: when to use and when to import.
    • Wildcard import: import java.util_
    • Name the class: import Java. Util. {arrarylist = > JL}
    • Import multiple classes of the same package: imprt Java. Util. {HashSet, ArrayList}
    • Shielding class: import Java. Util. {arrarylist = > -, -}
    • Absolute path of import package: new_root_.java.util.HashMap
    • Note: the three default imports in Scala are
      • import java.lang._
      • import scala._
      • import scala.Predef._

Classes and objects

  • Class: can be regarded as a template

  • Object: represents concrete things

  • Defining classes: there is no public in scala. Multiple classes can be written in one. Scala

  • Basic syntax:

  • explain:

    • In Scala syntax, classes are not declared public. All these classes have public visibility (that is, public by default)
    • A Scala source file can contain multiple classes
  • Attributes: attributes are part of a class

    • Basic syntax: [modifier] var|val attribute name [: type] = attribute value
      • Note: the Bean attribute (@ BeanPropetry) can automatically generate standard setXxx/getXxx methods

encapsulation

  • Encapsulation is to encapsulate the abstract data and the operation on the data. The data is protected internally. Other parts of the program can operate on the data only through authorized operations. Java encapsulation operations are as follows:
    • Privatize properties
    • Provides a public set method for assigning values to attributes
    • Provide a public get method to get the value of the property
  • The public attribute in scala is actually private at the bottom, and it is operated through the get method and set method. Therefore, there are no operations like java, but in order to need these operations sometimes, Scala defines an annotation (@ BeanProperty) for implementation
  • Access rights
    • The default access permission of properties and methods in Scala is public, but there is no public keyword in Scala
    • Private is a private permission, which is only available in the interior of a class and its associated objects
    • Protected is the protected permission. The protected permission in Scala is more strict than that in Java. The same kind and subclass can be accessed, but the same package cannot be accessed
    • private [package name] adds package access permission. Other classes under the package name can also be used
  • method
    • Basic syntax: def method name (parameter list) [: return value type] = {method body}
  • Create object: val | var object name [: type] = new type ()
    • val modifies an object. You can't change the reference of the object. You can change the value of the object attribute
    • var modifies an object. You can modify the reference of the object and modify the attribute value of the object
    • Auto derived variable types cannot be polymorphic, so polymorphic declarations need to be displayed
  • Constructor: like Java, Scala construction objects also need to call construction methods, and there can be any number of construction methods. Constructors include: Main constructors and auxiliary constructors
    • Auxiliary constructor. The name of the function is this. There can be multiple functions. The compiler distinguishes them by the number and type of parameters
    • The auxiliary constructor method cannot directly build an object, and the main constructor method must be called directly or indirectly
    • When the constructor calls another constructor, the called constructor must be declared in advance
    • Basic syntax: class class name (formal parameter list) {/ / main constructor / / class body def this (formal parameter list) {/ / auxiliary constructor def this (formal parameter list) {/ / auxiliary constructor can have multiple...}}
  • Constructor parameters: the formal parameters of the main constructor function of Scala class include three types: without any modification, var modification and val modification
    • Without any modifiers, this parameter is a local variable
    • var modifier parameter, used as a member attribute of a class, can be modified
    • The val modifier parameter is used as a read-only attribute of the class and cannot be modified

Inheritance and polymorphism

  1. Basic syntax: class subclass name extends parent class name
    • Subclasses inherit the properties and methods of the parent class
    • scala is single inheritance
    • Inherit call order: parent class constructor - child class constructor
    • Properties and methods in scala are dynamically bound, while only methods in java are dynamically bound
  2. Case practice:
class Person(nameParam:String){
  var name=nameParam
  var age:Int=_
  def this(nameParam:String,ageParam:Int){
    this(nameParam)
    this.age=ageParam
    println("Parent auxiliary constructor")
  }
  println("Parent class main constructor")
}

class Emp(nameParam:String,ageParam:Int)extends
  Person(nameParam,ageParam){
  var empNo:Int=_
  def this(nameParam:String,ageParam:Int,empNoParam:Int){
    this(nameParam,ageParam)
    this.empNo=empNoParam
    println("Auxiliary constructor for subclasses")
  }
  println("Subclass main constructor")
}
object Test{
  def main(args:Array[String]):Unit={
    new Emp("z3",11,1001)
  }
}

//Dynamic binding
class Person {
  val name: String = "person"
  def hello(): Unit = {
    println("hello person")
  }
}
class Teacher extends Person {
  override val name: String = "teacher"
  override def hello(): Unit = {
    println("hello teacher")
  }
}
object Test {
  def main(args: Array[String]): Unit = {
    val teacher: Teacher = new Teacher()
    println(teacher.name)
    teacher.hello()
    val teacher1:Person = new Teacher
    println(teacher1.name)
    teacher1.hello()
  }
}

Abstract properties and abstract methods

  1. Basic syntax:
    • Define abstract class: abstract class Person()
    • Define abstract attribute: an attribute is not initialized, that is, the abstract attribute val|var name:string
    • Defining abstract methods: only declaring but not implementing methods is the abstract method def hello():string
  2. Inheritance and override:
    • If the parent class is an abstract class, the child class needs to implement the abstract properties and methods, otherwise the child class also needs to be declared as an abstract class
    • Overriding a non abstract method needs to be modified with override, and overriding an abstract method can be done without override
    • The method to call the parent class in the subclass uses the super keyword.
    • The subclass implements the abstract attribute, and the abstract attribute of the parent class can be modified with var
      • The subclass overrides the non Abstract attribute. The non Abstract attribute of the parent class only supports val type, not var
      • Because var is modified as a variable, it can be used directly after subclass inheritance, and there is no need to rewrite it
  3. Anonymous subclass: like Java, you can create an anonymous subclass by including code blocks with definitions or overrides
abstract class Person {
  val name: String
  def hello(): Unit
}
object Test {
  def main(args: Array[String]): Unit = {
    val person = new Person {
      override val name: String = "teacher"

      override def hello(): Unit = println("hello teacher")
    }
  }
}

Singleton object (companion object)

  • Scala is a completely object-oriented language, so there is no static operation. However, in order to interact with the java language, a special object is generated to simulate the class, which is a singleton object. If the singleton object is consistent with the class name, it is called the companion object of this class, and all "static" contents of this class can be declared in its companion object.
  • Basic syntax:
	object Person{
		val country:String="China"
	}
  • explain:
    • The singleton object is declared with the object keyword
    • The class corresponding to a singleton object is called a semigenerative class, and the name of the associated object should be consistent with the name of the associated class
    • The properties and methods in the singleton object can be accessed directly through the associated object name
  • code:
    • \When a class represents a student, because the school is fixed, there is no need to input. At this time, the accompanying object is required
    • After adding companion objects
  • apply method
    • explain:

      • Through the apply method of the associated object, you can create an object without using the new method
      • If you want to make the main constructor private, you can add private before ()
      • The apply method can be overloaded
      • The obj statement in Scala actually calls the apply method of the object, object.apply, to unify the style of object programming and functional programming
      • When you use the new keyword to build an object, you actually call the construction method of the class. When you directly use the class name to build an object, you actually call the apply method of the associated object
    • code:

      • Normally, when we create an object, a new one will appear, as shown in the following figure
      • However, when we want private construction methods, like factory mode, without directly creating objects, we can't directly new
    • So the apply method is needed at this time

      *Apple also has a feature that can be omitted

Idiosyncrasy

  • In Scala language, trait is used to replace the concept of interface, that is, when multiple classes have the same trait, this trait can be independent and declared by keyword trait.
  • Traits in Scala can have both abstract attributes and methods and concrete attributes and methods. A class can be mixed with multiple characteristics. This feeling is similar to that of abstract classes in JAVA.
  • Scala introduces the trait feature. First, it can replace the Java interface. Second, it is also a supplement to the single inheritance mechanism.
  • Syntax:
trait Trait name{
	trait subject
}
  • If a class has a certain trait, it means that it meets all the elements of the trait. Therefore, the extends keyword is also used. If there are multiple traits or parent classes, the with keyword needs to be used for connection.
  • Basic syntax:
    • No parent class: class name extends trait 1 with trait 2 with trait 3
    • Parent class: class name extends parent class
    • Traits can have both abstract and concrete methods
    • A class can mix in multiple traits
    • All Java interfaces can be used as Scala features
    • Dynamic blending: flexible extension of class functions
      • Dynamic blending: when creating an object, you blend the trait without having to mix the class into the trait
      • If there are unimplemented methods in the mixed trait, they need to be implemented
  • code:
trait PersonTrait {
  //(1) Traits can have both abstract and concrete methods
  // Declare properties
  var name: String = _
  // Abstract properties
  var age: Int

  // Declaration method
  def eat(): Unit = {
    println("eat")
  }

  // Abstract method
  def say(): Unit
}

trait SexTrait {
  var sex: String
}

//(2) A class can implement / inherit multiple attributes
//(3) All Java interfaces can be used as Scala features
class Teacher extends PersonTrait with java.io.Serializable {
  override def say(): Unit = {
    println("say")
  }

  override var age: Int = _
}

object TestTrait {
  def main(args: Array[String]): Unit = {
    val teacher = new Teacher
    teacher.say()
    teacher.eat()
    //(4) Dynamic blending: flexible extension of class functions
    val t2 = new Teacher with SexTrait {
      override var sex: String = "male"
    }
    //Call the properties of the blend trait
    println(t2.sex)
  }
}
  • Trait superposition: because a class can be mixed with multiple traits, and there can be specific attributes and methods in the traits, if the mixed traits have the same methods, there will be inheritance conflict.
    • First, a class is mixed with two characteristics with the same specific methods, and there is no relationship between the two characteristics. If you want to solve this method, you need to override the conflicting methods in the class
    • Second, a class has the same specific method for mixing two traits, and the two traits inherit from the same trait. In order to solve this conflict problem, we need to adopt the strategy of trait superposition
      • When a class is mixed with multiple traits, scala will sort all traits and their parent traits in a certain order, and the super.describe() in the following case actually calls the describe() method in the next trait after ranking.
        • In other words, super in the case does not represent its parent trait object, but the next trait in the above superposition order, that is, super in MyClass refers to Color, super in Color refers to Category, and super in Category refers to Ball.
        • If you want to call a specified method mixed into the trait, you can add a constraint: Super [], such as super[Category].describe().
  • code:
trait Ball {
 def describe(): String = {
 "ball"
 }
}
trait Color extends Ball {
 override def describe(): String = {
 "blue-" + super.describe()
 }
}
trait Category extends Ball {
 override def describe(): String = {
 "foot-" + super.describe()
 }
}
class MyBall extends Category with Color {
 override def describe(): String = {
 "my ball is a " + super.describe()
 }
}
object TestTrait {
 def main(args: Array[String]): Unit = {
 println(new MyBall().describe())
 }
}
  • Trait self type
    • Note: its own type can realize the function of dependency injection
    • Case practice:
class User(val name: String, val age: Int)
trait Dao {
 def insert(user: User) = {
 println("insert into database :" + user.name)
 }
}
trait APP {
 _: Dao =>
 def login(user: User): Unit = {
 println("login :" + user.name)
 insert(user)
 }
}
object MyApp extends APP with Dao {
 def main(args: Array[String]): Unit = {
 login(new User("bobo", 11))
 }
}

Type checking and conversion

  • explain:
    • obj.isInstanceOf[T]: judge whether obj is of type T.
    • obj.asInstanceOf[T]: strongly convert obj to T type.
    • classOf gets the class name of the object.
  • Case practice:
class Person{
}
object Person {
 def main(args: Array[String]): Unit = {
 val person = new Person
 //(1) Determine whether the object is an instance of a type
 val bool: Boolean = person.isInstanceOf[Person]
 if ( bool ) {
 //(2) Converts an object to an instance of a type
 val p1: Person = person.asInstanceOf[Person]
 println(p1)
 }
 //(3) Get class information
 val pClass: Class[Person] = classOf[Person]
 println(pClass)
 }
}

Enumeration class and application class

  • explain:
    • Enumeration class: it needs to inherit enumeration
    • Application class: need to inherit App
  • Case practice:
object Test {
 def main(args: Array[String]): Unit = {
 println(Color.RED)
 }
}
// Enumeration class
object Color extends Enumeration {
 val RED = Value(1, "red")
 val YELLOW = Value(2, "yellow")
 val BLUE = Value(3, "blue")
}
// Application class
object Test20 extends App {
 println("xxxxxxxxxxx");
}

Type defines a new type

  • Note: use the type keyword to define a new data type name, which is essentially an alias of the type
  • Case practice:
object Test {
 def main(args: Array[String]): Unit = {
 
 type S=String
 var v:S="abc"
 def test():S="xyz"
 }
}

Posted by luisluis on Sat, 09 Oct 2021 00:11:15 -0700