类
类是某一种或者某一类东西的抽象(人、猫、狗–>生物)
class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class People(){
var name:String = ""
var city:String = ""
def eat(): Unit ={
println(this.name + "eat ....")
}
def py(pyName:String): Unit ={
println(this.name + "正在跟" + pyName + "xxxx...")
}
}
----------
- 通过class关键字进行类的定义
- 属性:name、city
- 方法:eat、py
调用
1
2
3
4
5
6
7
8val people = new People()
people.name = "大树"
people.city = "北京"
people.eat()
-----------
- 对象通过new关键字进行新建
- 属性和方法的调用通过.占位符
1
2
3
4
5
6
7
8
9
10var sex = _
Double:0.0
Int:0
String:null
Boolean:false
-------
- 定义属性的时候使用_代表占位符
- 如果使用了占位符必须要声明变量的类型
- 使用占位符会有默认值链式编程的实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33实现目标:val conf = new SparkConf().setAppName(appName).setMaster(master)
---------------------
class SparkConf{
var setting = new ConcurrentHashMap[String,String]
// 底层是一个map
private[this] def set(key:String,value:String): SparkConf ={
setting.put(key,value)
this
}
def setMaster(master:String): SparkConf ={
set("spark.master",master)
}
def setAppName(name:String): SparkConf ={
set("spark.app.name",name)
}
def printInfo(): Unit ={
println(setting.get("spark.master") + setting.get("spark.app.name"))
}
}
----------------------
val sparkConf = new SparkConf()
sparkConf.setMaster("yarn").setAppName("SparkConfApp")
sparkConf.printInfo
----------------------
- 这里我们的setXXX函数返回了一个当前对象,这样我们就能够实现链式编程的核心
- set函数我们使用了private[this]关键字进行了定义,这样set方法就只能在本类调用,在外部就没办法进行调用了
类-源码结合
pom.xml
1
2
3
4
5
6
7
8<spark.version>2.4.0</spark.version>
<!--sparkCore依赖-->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>${spark.version}</version>
</dependency>SparkConf.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24private[spark] def set(key: String, value: String, silent: Boolean): SparkConf = {
if (key == null) {
throw new NullPointerException("null key")
}
if (value == null) {
throw new NullPointerException("null value for " + key)
}
if (!silent) {
logDeprecationWarning(key)
}
settings.put(key, value)
this
}
/**
* The master URL to connect to, such as "local" to run locally with one thread, "local[4]" to
* run locally with 4 cores, or "spark://master:7077" to run on a Spark standalone cluster.
*/
def setMaster(master: String): SparkConf = {
set("spark.master", master)
}
-----------
这里可以看到跟我们demo的写法是一致的
构造器方法
主构造器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Person(val name:String,val city:String){
println("Person Enter...")
def eat(): Unit ={
println(name + "eat....")
}
}
val person = new Person("大树","北京")
person.eat()
------------
Person Enter...
大树eat....
- 在class后面的内容就是主构造器
- 我们在定义类的时候指定了属性,就可以通过传参的方式直接构建对象附属构造器
1
2
3
4
5
6
7
8
9
10
11var age:Int = _
// 附属构造器
def this(name:String,city:String,age:Int){
this(name,city)
this.age = age
}
val person2 = new Person("小花","盐城",18)
--------------------
附属构造器必须调用主构造器或者其他构造器