Six, Scala eleven object-oriented programming from entry to the master (primary)

6, object-oriented programming

6.1 Classes and Objects

->

Granny Zhang raised only cats: a name is white, 3 years old, white. Also called a floret, 10 years old this year, suit. Write a program, when the user enters the name of the cat, the cat will display the name, age, color. If the kitten wrong name entered by the user is displayed Granny Zhang not only cats.

// problem
cat has three attributes, not the same type.
If a variable using common bad management
uses a new data type ((1) can manage multiple different types of data [attributes]) (2) can attribute operation - method
therefore the object class

6.1.1, Scala is an object-oriented language

1, Java is an object-oriented programming language, for historical reasons, Java, there are still non-object-oriented content: basic types, null, static methods.
2, Scala language from Java, so inherently object-oriented language, and Scala is a pure object-oriented language that in Scala, everything is an object.

3, in the object-oriented learning process can be compared with the Java language learning

6.1.2 Quick Start - object-oriented way to solve the problem of cats

object CatDemo {
  def main(args: Array[String]): Unit = {
    // 创建一个猫
    val cat = new Cat
    // 给猫的属性赋值
    // 说明
    // 1. cat.name=“小白” 其实不是直接访问属性,而是 cat.name_$eq("小白")
    // 2. cat.name 等价于 cat.name()
    cat.name = "小白" // 等价
    cat.age = 10
    cat.color = "白色"
    println("ok···")
    printf("\n小猫的信息如下:%s,%d,%s",cat.name,cat.age,cat.color)
  }
}
// 定义一个类
// 一个class Cat 对应的字节码文件只有一个Cat.class,默认是public
class Cat {
  // 声明3个属性
  // 说明
  // 1.当我们声明了 var name :String 时,在底层对应private name
  // 2.同时会生成 两个public方法 name() <=类似=> getter  name_$et() => setter
  var name:String = "" // 给初始值
  var age:Int = _ // _ 表示给age 一个默认的值,如果是Int,默认就是0
  var color:String = _ // _给 color 默认值,如果时String,默认就是""

}

6.1.3 Classes and Objects of the differences and connections

Through the above cases and explain that we can see:

1, the class is abstract, conceptual, on behalf of a class of things, such as humans, cats ...
2, the object is concrete, practical, on behalf of
a specific
thing
3, class is a template object, the object is an individual class, corresponds to an example
4, Scala classes and objects and Java differences and connections are the same.

6.1.4 How to define a class

-> basic grammar

[Modifier] class class name {
class body
}

Precautions class definition
scala syntax, the class is not declared as public, all of these classes have public visibility (which is the default is public), [modifier and then explain later].
A Scala source file can contain multiple classes.

6.1.5, property

basic introduction

Case presentation:

class Dog{
  var name = "jack"
  var lover = new Fish
}

Attribute is part of a class, generally value data types , but also a reference type . For example, we defined earlier age cats is property

6.1.6, attributes / member variables

Notes and detailed instructions

1) with the variables defined property syntax, examples: [access modifiers] var attribute name [: type] attribute value =

2) define types of attributes may be of any type, including a reference type or a value type [ Case Demo]

3) Scala a declared property, initialization must be displayed, and depending on the type of the initialization data automatically inferred attribute type can be omitted (this is unlike Java).

4) If the assignment is null type must be added, because without type, the type of the property is Null type.

object PropertyDemo {
  def main(args: Array[String]): Unit = {
    val p1 = new Person
    println(p1.Name) // Null
    println(p1.address) // String
  }
}

class Person {
  var age: Int = 10 // 给属性赋初始值,省略类型,会自动推导
  var sal = 8090.9
  var Name = null // Name 是什么类型
  var address: String = null // ok
}

5) If the definition of property, not this assignment, you can also use the symbol ** _ (underscore), so that the same below ** assign default values

6) different objects properties are independent of each other, to change the properties of an object does not affect the other.

Case Presentations + column chart (Monster) // This is exactly the same and Java

def main(args: Array[String]): Unit = {
var worker1 = new Worker
worker1.name = "jack"
var worker2 = new Worker
worker2.name = "tom"
}
class Worker {
  var name = ""
}

6.1.7, the advanced section of the property

Description : The property of the Advanced section and constructors (constructor / functions) related, we have advanced into some of the properties where the constructor to explain

6.1.8 How to create objects

The basic syntax

val | var object name [: Type] = new type ()

Description:

1) If we do not want to change the reference object (ie: memory address) should be declared as a val nature, or declared as var, scala val designers recommended, because, in general, in the program, we just change the subject property value, rather than changing the object's reference

2) scala When you declare an object variable, depending on the type can be inferred automatically create objects, so type declaration can be omitted, but when behind the new object types and type inheritance relationship that is multi-state, it is necessary to write

object CreateObj {
  def main(args: Array[String]): Unit = {
    val emp = new Emp // emp 类型就是Emp
    // 如果我们希望将子类对象,交给父类的引用,这时就需要写上类型
    val emp2:Person = new Emp

  }
}
class Person{

}

class Emp extends Person{

}

6.1.9, memory allocation mechanism of classes and objects

object MemState {
  def main(args: Array[String]): Unit = {
    val p1 = new Person2
    p1.name = "jack"
    p1.age = 10

    val p2 = p1
    println(p1 == p2) // true
    p1.name = "tom"
    println(p2.name)  // tom
  }
}

class Person2 {
  var name = ""
  var age: Int = _ // 如果是以_ 的方式给默认值,则属性必须指定类型
}

Here Insert Picture Description

6.2 Method

6.2.1 Basic instructions

In Scala is to function

6.2.2 The basic grammar

def method name (parameter list) [: Return Value Type] = {

The method body

}

6.2.3 The method of case presentations

object MethodDemo01 {
  def main(args: Array[String]): Unit = {
    // 使用一下
    val dog = new Dog
    println(dog.cal(10,30))
  }
}
class Dog {
  private var sal: Double = _
  var food:String = _

  def cal(n1: Int, n2: Int): Int = {
    n1 + n2
  }
}

6.2.4 Principle call mechanism, method

  1. When we started scala, first opened a main stack in the stack area. main stack is the last to be destroyed
  2. When the scala program to execute a method, always open a new stack.
  3. Each stack is a separate space, the variables (basic data types) are independent, not affect each other (except a reference type)
  4. When the method is finished, the process will be open recovered jvm stack machine.

Related exercises 6.2.5, Method

1, write a class (MethodExec), a programming method, the method takes no parameters, a print rectangle 10 * 8 in the method, the method is called in the main process.

object MethodDemo02 {
  def main(args: Array[String]): Unit = {
    val m = new MethodExec
    m.printRect()
  }
}
class MethodExec {
  def printRect(): Unit = {
    for (i <- 0 until (10)) {
      for (j <- 0 until (8)) {
        print("*")
      }
      println()
    }
  }
}

2, on a modified procedure, a write method, the method does not require parameters, calculates the area of ​​the rectangle, and a method as a return value. The method is called in the main process, and receiving the return value of the print area (the result of two decimal places).

m.len = 2.1
m.width = 3.4
println("面积等于="+m.area())
def area() ={
  (this.len * this.width).formatted("%.2f")
}

3, on a modified procedure, a write method, providing two parameters m and n, a printing method, the m * n rectangle, and then write a calculation method of the rectangular area (length len may be received, and wide width), the as a method return value. The method is called in the main process, receiving the return value and print area.

object MethodDemo02 {
  def main(args: Array[String]): Unit = {

    val m = new MethodExec

    m.len
    m.width
    m.printRect()
    println(m.area())

  }
}

class MethodExec {
  // 属性
  println("请输入矩形的长:")
  var len = StdIn.readInt()
  println("请输入矩形的宽")
  var width = StdIn.readInt()

  def printRect(): Unit = {
    for (i <- 0 until (len)) {
      for (j <- 0 until (width)) {
        print("*")
      }
      println()
    }
  }

  // 计算面积的方法
  def area(): Int = {
    this.len * this.width
  }
}

4, the preparation method of: determining a number is odd or even-odd

object MethodDemo03 {
  def main(args: Array[String]): Unit = {
    val o = new ood
    o.n
    o.decide()
  }
}

class ood {
  println("请输入一个数字:")
  var n = StdIn.readInt()

  def decide() = {
    if (n % 2 == 0) {
      println("你输入的数字为偶数")
    } else {
      println("你输入的数字为奇数")
    }
  }
}

5, a small calculator (Calcuator), to achieve four arithmetic functions

1, four complete method

2, a sub-method is completed

object MethodDemo04 {
  def main(args: Array[String]): Unit = {
    val c = new Calcuator
    c.n1
    c.n2
    c.symbol
    c.cal()
  }
}
class Calcuator {
  println("请输入两个数字:")
  var n1 = StdIn.readDouble()
  var n2 = StdIn.readDouble()
  println("请输入运算符:")
  var symbol = StdIn.readChar()

  def cal()= {
    if (symbol == '+') {
      println(n1 + n2)
    } else if (symbol == '-') {
      println(n1 - n2)
    } else if (symbol == '*') {
      println(n1 * n2)
    } else if (symbol == '/') {
      println(n1 / n2)
    }else{
      println("你的输入有误,请重新输入···")
    }
  }
}

6.3 Classes and Objects Applications

1, seen cases of puppy

1, the preparation of a Dog class that contains the name (String), age (Int), weight (Double) property

2, say a method declared in the class, String two return type, the method returns information includes all attribute values

3, the main method TestDog ​​another class, create a Dog object, and ask all say the methods and properties, will call the printout.

object DogCaseTest {
  def main(args: Array[String]): Unit = {
    val dog = new Dog
    dog.name = "tom"
    dog.age = 2
    dog.weight = 6
    println(dog.say())
  }
}
class Dog {
  var name: String = ""
  var age: Int = 0
  var weight: Double = 0.0
  def say(): String = {
    "小狗的信息如下:\n name = " + this.name +
      "\n age =" + this.age +
      "\n weight = " + this.weight
  }
}

2, Box Case

1, to create a programmed Box class, which defines three variables represented in a cube of length, width and height, length and breadth can be input through the console

2, defines a method of obtaining the volume of a cube (Volumn) L * W * H

3, an object is created, the volume of a given print size cube

object BoxCaseTest {
  def main(args: Array[String]): Unit = {
    val b  = new Box
    b.len
    b.width
    b.hieght
    b.volumn()
  }
}

class Box{
  println("请输入立方体的长、宽和高:")
  var len = StdIn.readDouble()
  var width = StdIn.readDouble()
  var hieght = StdIn.readDouble()
  def volumn(){
    println("立方体的体积:"+(this.len * this.width * this.hieght))
  }
}

3, scenic spots seen cases

  • 1, a scenic spot ticket charges unreasonable price depending on the age of someone

  • 2, write swim humans, according to age group decided to purchase the ticket price and output

  • 3. Rules: age> 18, tickets for 20, otherwise free

  • 4, can be recycled from the console to enter the name and age of the print ticket fees, if the name entered n, then exit the program.

  • object TicketsTestDemo {
      def main(args: Array[String]): Unit = {
        val t = new Tourist
        t.name
        t.age
        t.rule()
    
      }
    }
    
    class Tourist {
      println("请输入你的姓名和年龄:")
      var name = StdIn.readChar()
      var age = StdIn.readInt()
    
      def rule() = {
        if (name == 'n') {
          println("退出程序")
        }
        else if (age > 18) {
          println("%s先生您好,您的年龄为%d,门票为20元".format(name, age))
        } else if (age <= 18) {
          println("%s先生您好,您的年龄为%d,门票免费".format(name, age))
        }
      }
    }
    

6.4, constructor

6.4.1, see a demand

Let's look at a demand: in front of us in the Person object creation is first an object is created later, give his age and name attribute assignment, I asked if now, when you create a human subject, directly specify the and the name of the object's age, how to do? then you can use the constructor / builder.

6.4.2, the basic description

Constructor (constructor) constructor method called , is a special type of a method, its main function is to complete the initialization of the new object.

6.4.3, Scala constructor Introduction

Like Java, Scala also need to construct the object constructor call, and can have any number of constructors (that is, the scala overloaded constructor is also supported).

Scala class constructor comprising: a main configuration and secondary builder

6.4.4 The basic syntax Scala constructor

class class name (parameter list) {// constructor main

// class body

def this (parameter list) {// auxiliary builder

}

def this (parameter list) {// constructor may have a plurality of auxiliary ...

}

}

6.4.5, Quick Start Scala constructor

age and name attribute values ​​of attribute values ​​to create a Person object while the object is initialized

object ConDemo01 {
  def main(args: Array[String]): Unit = {
    val p = new Person("jack", 20)
    println(p)
  }
}

// 构造器的快速入门
//创建Person对象的同时初始化对象age属性值和name属性值
class Person(inName: String, inAge: Int) {
  var name: String = inName
  var age: Int = inAge

  // 重写toString,便于输出对象的信息
  override def toString: String = {
    "name = "+this.name +"\n"+ "age = "+this.age
  }
}

6.4.6, Scala constructor considerations and details

1, Scala constructor is to be accomplished for the new object is initialized, the constructor has no return value

2. Statement of the primary constructor placed directly after the class name [ decompile]

3, all statements performs the primary constructor class definition , here we appreciate Scala functional programming and object-oriented programming ** together, namely: is the constructor method (function), passing parameters and methods of use, and part of the function does not differ from the foregoing [column text presentation + recompilation] (the main class constructor is actually part of the other member which in addition to the function is executed) **

4, parentheses constructor is called if the constructor five primary parameters, parentheses may be omitted, constructed object can be omitted

5, the auxiliary builder name for this (and this is not the same Java), a plurality of auxiliary builder are distinguished by different parameter list, at the bottom is overloaded constructor java

object ConDemo02 {
  def main(args: Array[String]): Unit = {
    val a = new AA("")
    // 输出的顺序是
    // 1、b···  父类
    // 2、AA() 构造器
    // 3、A this(name:String) 辅助构造器
  }
}

class BB() {
  println("b···")
}

class AA() extends BB() {
  println("AA()")
  def this(name: String) {
    this // 调用A的柱构造器
    println("A  this(name:String)")
  }
}
object ConDemo03 {
  def main(args: Array[String]): Unit = {
    val p1 = new Person2()
    println(p1)
  }
}

// 定义了一个Person类
// 运行后Person 有几个构造器  4
class Person2(){
  var name:String = _
  var age:Int = _
  def this(name:String){
    /*辅助构造器无论是直接还是间接,最终都一定艺调用主构造器,执行
主构造器的逻辑,而且需要放在辅助构造器的第一行[这点和Java一样,java
中一个构造器要调用同类的其他构造器,也需要放在第一行]
     */
    this() // 直接调用主构造器
    this.name = name
  }
  // 辅助构造器
  def this(name:String,age:Int){
    this()
    this.name = name
    this.age = age
  }
  def this(age:Int){
    this("匿名") // 间接调用主构造器,因为 def this(name :String)中调用了主构造器
    this.age = age
  }
  def showinfo():Unit={
    println("person的信息如下:")
    println("name="+this.name)
    println("age="+this.age)
  }

  override def toString: String = {
    this.name+this.age
  }
}

6, if you want to become the master private constructor may re () before adding private, so that users can be constructed by the object constructor auxiliary

class Person2 private(){}

7, auxiliary constructor can not be declared and declare the main constructor of the same, an error will occur (ie constructor with that name repeat)

6.5 Properties Advanced

6.5.1, configuration parameters

1, the main Scala class constructor parameter is not modified with any modifier, then this parameter is a local variable.

// 1.如果 主构造器是Worker(inName:String),  那么 inName就是一个局部变量
class Worker(inName:String){
  var name = inName
}

2, if the parameter val keyword to declare, then Scala will use parameters as a private read-only attribute class

// 2.主构造器是Worker(val inName:String),那么 inName就是Worker2的一个private的只读属性
class Worker2(val inName:String){
  var name = inName
}

3, if the parameter using var keyword to declare, then it will Scala parameters as class member properties to use, and will provide the corresponding attribute xxx () [similar getter] / xxx_ $ eq () [ similar setter] method, namely that when a member property is private, but can read and write .

// 3.主构造器是Worker(var inName:String), 那么 inName就是Worker2的一个private的可读写属性
class Worker3(var inName:String){
  var name = inName
}

6.5.2, Bean Properties

JavaBeans specification is a Java properties like getxxx () and setxxx () method . Many Java tools rely on this naming convention. For Java interoperability. The Scala field plus @BeanProperty when this specification is automatically generated ** setxxx / getxxx method. ** then you can use the object .setxxx () and getxxx () to call the property.

Note : After addition of an attribute to @Beanproperty annotations, and generates getxxx setxxx methods, and automatically generate a similar underlying the original xxx (), xxx - $ eq ( ) method, there is no conflict, both can coexist

import scala.beans.BeanProperty
object BeanPropertyDemo01 {
  def main(args: Array[String]): Unit = {
    val car = new Car
    car.name = "宝马"
    println(car.name)

    // 使用 @BeanProperty 自动生成getXxx 和 setXxx
    car.setName("奔驰")
    println(car.getName)
  }
}

class Car{
  @BeanProperty var name:String = null
}

6.6, object creation process scala analysis (interview questions)

class Person{
    var age:Short = 90
    var name:String = _
    def this(n:String,a:Int){
        this()
        this.name = n
        this.age  = a
    }
var p : Person = new Person("小倩"20)

1, the information loaded classes (attribute information, the information method)

2, in memory (heap) open space

3, using the parent class constructor (primary and secondary) initial

4, using the main attributes constructor initializes [age: 90, naem nul]

5, the use of auxiliary builder are initialized [age: 20, naem Xiaoqian]

6, will open up the address of an object is assigned to this reference p

Published 16 original articles · won praise 22 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_44258756/article/details/105271384