Scala object oriented (OOP)

I class

  • Class is defined by the class keyword
  • Class creates an instance through the new keyword
  • Class has member variables and methods
  • Class members are public by default. private and protected are also supported
  • Static member variables and methods cannot be defined in a class
  • Class does not need to explicitly define the construction method, and is declared as part of the class through the construction parameter list

1. Class member access modifier

2. Definition of class

Constructor:
primary constructor
Auxiliary constructor (from construction method)
Member variables and methods
Instantiated class

3. Inheritance of classes

  • Scala uses the "extends" keyword to implement inheritance
  • Subclass overriding parent class methods must use the 'override' keyword

II Singleton object

Question: static members cannot be defined in Scala classes, that is, there is no static keyword. How to express static member variables, member methods and static code blocks of a class like Java?
Scala solution: singleton object
1. Use the keyword "object" to declare, which can include variables, methods and code definitions
2. The member variables and methods in the singleton object are called directly through the singleton object name
3. The singleton object is initialized when it is accessed for the first time, and all code blocks are executed
4. The singleton object cannot be new and has no construction parameters
5. The program entry main() method must be defined in the singleton object
6. A binding relationship is formed when a singleton object and a class with the same name are defined in the same file

//Defining singleton objects
object Blah {
  println("Blah initializing...")
  def sum(l: List[Int]): Int = l.sum
}
test.Blah.sum(List[Int](1, 2, 3, 4, 5))

3, Associated classes and associated objects

  • The associated class and associated object are in the same file with the same name
  • The calss class is called the companion class of Object
  • Object is called the companion object of class
  • Associated classes and associated objects can access their private members
  class Person (uname:String,uage:Int){
    //scala main constructor, which is defined at the head of the class
    println("class Enter into person of class In class")
    var name:String=uname
    var age:Int=uage
    private var address: String = "Asia"

    def this(){
      this("xxx",0)
      println("class this() From construction method")
    }
    def this(age:Int){
      this("sss",age)
    }
  def this(name:String){
    this(name,0)
  }
    println("class The variable definition is completed and the method is ready to be defined")

    def printmsg(): Unit = {
      println(Person.name + Person.age + address)
    }

    println("class Like a swim, ready to leave person class")
  }

  object Person { //Static classes similar to Java
    //It is the companion of calss person
    println("object Enter into Person Among the accompanying objects...")
    private val name: String = "China"
    private val age: Int = 71

    def apply(uname: String, uage: Int): Person = new Person(uname, uage)

    def apply(uname: String): Person = new Person(uname)

  println(" object The variable definition is completed and the method is ready to be defined")
    def showmsg(): Unit = {
      println(Person.name + " " + Person.age)
    }

    def main(args: Array[String]): Unit = {
      println(" object main Enter into main Method")
//      var personNew: Person = new Person("zs",21)
//      var person = Person
//      person.showmsg()
//      personNew.printmsg()
//      var p1:Person=new Person()
//      var p2:Person=new Person(21)
//      var p3:Person=new Person("zhangsan")
      var po1=Person("zs",12)
//      val person=Person.apply("aa",12)
     val po2=Person("kb09")
    }
    println("object The accompanying object swims once and ends")
}

4, trait

There is no concept similar to the interface in Java in Scala, but the function of the interface needs to be used. Therefore, the concept of trait is introduced, which is similar to the function of the interface

  • Traits are defined using the "trait" keyword
  • The method in the implementation uses "override"
trait Type1{
   def fly():Unit={
   println("Like flying")
   }
 }
trait Type2{
  def biu():Unit={
    println("Like to call")
  }
}
trait type3{
  def run():Unit={
    println("Like running")
  }
}
abstract class Animal{
  def brand:String
  def appreance:String
}
class robit extends Animal with type3 {
  override def brand: String = {
    "Cross country rabbit"
  }
  override def appreance: String = {
    "black"
  }
}
class dog extends Animal with Type2 with Type1{
  override def brand: String = {
    "Siberian Husky"
  }
  override def appreance: String = {
    "white"
  }
}
  object Animal {
    def main(args: Array[String]): Unit = {
      val r: robit = new robit
      println(r.appreance)
      println(r.brand)
      r.run

      val d:dog=new dog
      println(d.appreance)
      println(d.brand)
      d.biu()
      d.fly()
    }
  }

The output results are as follows:

Mixed trait

  • When a trait is used to combine classes, it is called blending
  • A class can only have one parent class, but can have multiple blends (use the keywords extends and with respectively)

Selection of traits and abstract classes

  • Priority use characteristics

        1.Abstract classes can only inherit once
        2.Traits can be mixed into multiple
    
  • Use abstract classes when you need to construct methods with parameters

  • Interoperability with Java

    1.Abstract classes and Java Fully interoperable
    2.Features are interoperable only if they do not contain any implementation code
    

5, Type change

1. Generic class

Generic classes refer to classes that can accept type parameters. Generic classes are widely used in collection classes
Unlike Java, defining generic classes uses "[]"

2. Type change classification

Covariant: class Foo[+T] / / covariant class

  • For two types A and B, if a is a subtype of B, Foo[A] is a subtype of Foo[B]

Inversion: class Bar[-T] / / inversion class

  • For two types A and B, if a is a subtype of B, then Bar[B] is a subtype of Bar[A]

Invariant: class Baz[T] / / invariant class

  • By default, generic classes in Scala are invariant
object CovariantAndContravariant {
//Covariant point and inverse point invariant
  class Animal{
  def eat():Unit={
  println("Animals eat food")
  }
}
  class Cat extends Animal{
    override def eat():Unit=println("Cats eat fish")
  }
class Tiger extends Cat{
  override def eat():Unit=println("Tigers eat meat")
}
class Invariant[T] {  //unchanged
 }
class Covariant[+T]{} //covariant
  class Contravariant[-T]{} //Invert
  def main(args: Array[String]): Unit = {
  var cat=new Cat;
  val tiger=new Tiger;
  val cat2:Cat=tiger

    val bubianCat:Invariant[Cat]=new Invariant[Cat]
    val bubianTiger:Invariant[Tiger]=new Invariant[Tiger]  //unchanged
//    val bubianCat2:Invariant[Cat]=bubianTiger
    // An error is reported. When the generic example remains unchanged, Invariant[Cat] and Invariant[Tiger] do not have any variation

    val xiebianCat:Covariant[Cat]=new Covariant[Cat]
    val xiebianTiger:Covariant[Tiger]=new Covariant[Tiger]
    val xiebianCat2:Covariant[Cat]=xiebianTiger //covariant

    val nibianCat:Contravariant[Cat]=new Contravariant[Cat]
    val nibianTiger:Contravariant[Tiger]=new Contravariant[Tiger]
    val njbianTiger:Contravariant[Tiger]=nibianCat //Invert
  }
}

6, Packages and package objects

Reference to package:
import allows packages and members of package objects to be accessed directly by name
The format is usually: the package name referenced by import_

Tags: Scala

Posted by icesolid on Tue, 10 May 2022 03:55:49 +0300