2023_Spark_Experiment 5: Demonstration of Scala object-oriented part (1) (IDEA development)

1. The basic concept of object-oriented

Put the data and the operation method on the data together as an interdependent whole - object, oriented

Three characteristics of an object:

  •  encapsulation

  •  inherit

  •  polymorphism

2. Class definition

Simple classes and no-argument methods


class Counter{

private var value =0;

def increment() { value+=1};

def current() =value;

}



//注意:class 前面没有public 关键字修饰

If you want to develop the main method, you need to define the main method in the associated object of the class, that is: object pair

In the image, (detailed discussion will follow):


class Counter{

private var value =0;

def increment() { value+=1};

def current() =value;

}



//Scala 中类的定义

class Student1{

//定义属性

private var stuName:String = "Tom"

private var stuAge:Int =20



//成员方法

def getStuName():String = stuName

def setStuName(newName:String) =this.stuName=newName



def getStuAge():Int = stuAge

def setStuAge(newAge:Int) = this.stuAge=newAge

}



object student {

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

//测试student1

var s1 = new Student1



//第一次输出

println(s1.getStuName() + "\t" + s1.getStuAge())



//调用set方法

s1.setStuName("Mary")

s1.setStuAge(25)



//第二次输出

println(s1.getStuName() + "\t" + s1.getStuAge())



//第三次输出

// println(s1.stuName + "\t" + s1.stuAge)



}

}

3. Property getter and setter methods

When the defined property is private, scala will automatically generate the corresponding get and set methods for it, as follows

Show:

private var stuName:String = "Tom"

get method: stuName ----> s2.stuName() Since stuName is the name of the method, so

to add a parenthesis

set method: stuName_= ----> stuName_= is the name of the method

Define attributes: private var money:Int = 1000 I hope money only has a get method, no

set method? ?

Solution: define it as a constant private val money:Int = 1000

The usage of private[this]: this property is only private to the object, and no corresponding set and

get method. If so, it cannot be called directly, for example: s1.stuName ---> error


//属性的get 和 set 方法

/*

1.当定义属性是private 时候,scala会自动为其生成对应的get 和set方法

private var stuName:String = "Tom"

(1) get 方法:stuName ----> s2.stuName()

(2) set 方法:stuName_=



2.定义属性:private var money:Int = 1000 希望money只有get方法,没有set方法?

方法:将其定义为常量private val money:Int = 1000



3.private[this]

3.private[this]的方法:该属性只属于该对象私有,就不会生成对应的set和get方法

*/



class Student2 {

//定义属性

private var stuName:String = "Tom"

//private [this] var stuAge:Int =20

private var stuAge:Int = 20

private val money:Int = 1000



}



//测试

object Student2 {



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

var s2 = new Student2

println(s2.stuName + "\t" + s2.stuAge)

println(s2.stuName + "\t" +s2.stuAge + "\t" + s2.money)



//修改money的值 --》 error

//s2.money = 2000



}

}

4. Inner classes (nested classes)

We can define a class inside a class, as follows: In the Student class, we define

A Course class is used to save courses taken by students:


import scala.collection.mutable.ArrayBuffer



//嵌套类:内部类

class Student3 {

//定义一个内部类:记录学生选修的课程信息

class Course(val courseName:String,val credit:Int){

//定义其他方法

}

private var stuName:String = "Tom"

private var stuAge:Int = 20

//定义一个ArrayBuffer记录学生选修的所有课程

private var courseList = new ArrayBuffer[Course]()

//定义方法往学生信息中添加新的课程

def addNameCourse(cname:String,credit:Int): Unit ={

//创建新的课程

var c = new Course(cname,credit)

//将课程加入list

courseList += c

}

}



//测试

object Student3 {

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

//创建学生对象

var s3 = new Student3

//给该学生添加新的课程

s3.addNameCourse("Chinese",2)

s3.addNameCourse("English",3)

s3.addNameCourse("Math",4)

//输出

println(s3.stuName + "\t" + s3.stuAge)

println("*********选修课程***********")

for (s <-s3.courseList) println(s.courseName + "\t" + s.credit)

}



}

5. Class constructor

Class constructors are divided into: primary constructor, auxiliary constructor

Primary constructor: Combined with the declaration of the class, there can only be one primary constructor

Student4(val stuName:String,val stuAge:Int)

(1) Define the primary constructor of the class: two parameters

(2) Two attributes are declared: stuName and stuAge and the corresponding get and set methods

Auxiliary constructor: There can be multiple auxiliary constructors, implemented by the keyword this


/*

类的构造器

1.主构造器:和类的声明结合在一起;只能有一个主构造器

Student4(val stuName:String,var stuAge:Int)

(1)定义类的主构造器:两个参数

(2)声明了两个属性:stuName和stuAge 和 对应的get 和 set 方法

2.辅助构造器:可以有多个辅助构造器

通过关键字this 来实现

*/



class Student4 (val stuName:String,val stuAge:Int) {

//定义辅助构造器

def this(age:Int){

//调用主构造器

this("no name",age)

}

}



object Student4 {

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

//创建Student4的一个对象

var s4 = new Student4("Tom",20)

println(s4.stuName + "\t" +s4.stuAge)



//创建一个新的Student4 的对象

var s42 = new Student4(25)

println(s42.stuName + "\t" + s42.stuAge)

}



}

6. Object object in Scala

Scala does not have a static modifier, but the members under the Object object are all static, if there is a

class, which serves as its companion class. In Object, you can generally do some initialization and other operations for companion classes.

do. Following is an example of static block in Java. In this example, we initialize JDBC:

The Object in Scala is equivalent to the static block in Java.

In Scala, there is no such thing as static, but it also provides us with a singleton pattern

The way to achieve it is to use the keyword object.

When using the singleton pattern in Scala, in addition to the defined class, an object pair with the same name must be defined

Like, the difference between it and the class is that the object object cannot take parameters.

When a singleton object shares the same name with a class, it is said to be a companion object of that class:

companion object. You must define the class and its companion objects in the same source file. class is called

It is the companion class of this singleton object: companion class. A class and its companion objects can access each other

its private members.

Application of Object object

singleton object


//利用object 对象实现单例模式

object CreditCard {

//变量保存信用卡号,这里比较好的做法,是定义成private[this],即:该属性只属于该对象,这个方法由于定义在object中,所以是静态的,即:单例的



private[this] var creditCardNumber:Long = 0



//产生新的卡号

def generateNewCCNumber():Long = {

creditCardNumber += 1

creditCardNumber

}

//测试程序

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

//产生新的卡号

println(CreditCard.generateNewCCNumber())

println(CreditCard.generateNewCCNumber())

println(CreditCard.generateNewCCNumber())

println(CreditCard.generateNewCCNumber())

}

}

Use the application object: the main method can be omitted; it needs to be inherited from the parent class App.


//使用应用程序对象,可以省略main方法

object HelloWorld extends App{



/*

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

//这里的main就可以不写。相当于下面的代码是在main方法中执行的。

}

*/

println("Hello World")

///如何取得命令行的参数

if(args.length > 0) {

println(args(0))

}else{

println("no arguents")

}

}

Guess you like

Origin blog.csdn.net/pblh123/article/details/132624431