包在写代码的过程中,无处不在

 

class SQLContext private[sql](

    @transient val sparkContext: SparkContext,

    @transient protected[sql] val cacheManager: CacheManager,

    @transient private[sql] val listener: SQLListener,

    val isRootContext: Boolean)

  extends org.apache.spark.Logging with Serializable {

 

private[sql]是什么意思?

这里的意思是说,主构造器要在sql包下才能访问

 

import org.apache.hadoop.mapreduce.lib.input.{FileInputFormat => NewFileInputFormat}

这一句包的导入,同时也进行了重命名,FileInputFormat 重命名为 NewFileInputFormat

 

包的作用在于包可以很轻松地把自己的代码和别人的代码隔离开

 

package com.dt.spark.sql

 

 

class People {

  val counter = 3

  val counterArray=new Array[Int](counter)

}

 

class Sporter extends People {

  override val counter = 5

}

 

 

object OverrideField {

 

  def main(args:Array[String]){

    val sporter=new Sporter

    println(sporter.counterArray.length)  //the result is 0

  }

 

}

以上程序为什么结果是0呢?

是因为:在实例化的时候,People发现counter被复写了,所以reset为0,然后实例化counterArray的时候,就变成了0

可以改为:

class Sporter extends {

  override val counter = 5

} with People

可以先定义好counter,再混入People

这是Scala提前定义的语法

 

当然,我们也可以这样写:

abstract class People {

  val counter:Int

  val counterArray=new Array[Int](counter)

}

 

class Sporter extends People {

  override val counter = 5

}

 

但是这个其实还是0,和刚刚的机制是一样的

 

 

看一下Scala的继承结构:

Any相当于Java中的Object,几乎所有的类都会继承自Any类

关键在于,在这里有equals方法,要判断对象相等,就要复写它

 

一般复写equals方法都会复写hashcode方法,例子:

class Programmer(val name:String,val sal:Double){

  final override def equals(other:Any)={

    //两个对象真正相等的实际业务逻辑

    if(other!=null && other.isInstanceOf[Programmer]){

      val otherInstance=other.asInstanceOf[Programmer]

      this.name==otherInstance.name && this.sal==otherInstance.sal

    } else {

      false

    }

  }

 

  final override def hashCode() = name.hashCode()*7 + sal.hashCode()*9

 

 

}

 

归纳总结:1.看笔记

 

第十九课:Scala的包,继承复写

转载于:https://my.oschina.net/u/1449867/blog/730927

相关文章: