码迷,mamicode.com
首页 > 其他好文 > 详细

scala private private[package] protected 使用说明

时间:2015-01-26 19:16:08      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:scala   private   protected   

package com.scala.idle
object PrivateDoor {


  def main(args: Array[String]): Unit = {
    val privateContainer = new PrivateContainer()
    //访问共有变量
    println(privateContainer.publicVar)
    //调用共有方法
    privateContainer.showPublicMethod
    
    val privateClass = new PrivateClass
    privateClass.publicMethod
  }


}
class PrivateContainer{
  /**
   * 共有方法,外界的一个入口
   */
  def showPublicMethod = {
    showPrivateMethod
  }
  /**
   * 私有方法,外界不能直接访问.子类也不行
   */
  private def showPrivateMethod = {
    println("showPrivateFunction is a private function ,with a private variable : " + privateVar)
  }
  //共有变量
  val publicVar = "This is a public variable"
  //私有变量,外界无法访问。可以被showPrivateMethod方法访问
  private val privateVar = "This is a private variable"
}
/**
 * private class 作用于的范围:
 * 1 可以被同文件\相同包的其它class、object、trait调用
 * 2 可以被子package(递归所有的子包)的class、object、trait调用
 * 3 其它package中的元素是不可以调用该类的
 */
private class PrivateClass{
  
  //private 变量
  private val xxx = "xxx"
  //private 方法  
  private def showPrivateMethod = {
    println("showPrivateMethod is a private method of private class PrivateClass")
  }
  //共有方法,对外界保留的接口
  def publicMethod = {
    showPrivateMethod
  }

}


=============================================================================================================================

package org.cma.scala.scope


object HigherPrivate {


  def main(args: Array[String]): Unit = {
    val higherScope = new HigherScope()
    higherScope.useInCmaMethod
  }


}
class HigherScope{
  /**
   * private[cma] 控制了方法的可用范围:
   * 1 org.cma package中的元素可以使用该方法
   * 2 org.cma 子包(包含递归子包)中的元素可以使用该方法
   */
  private[cma] def useInCmaMethod = {
    println("you can use this method if you are in cma or the sub package")
  }
}

===================================================================================================

package com.scala.idle


object ProtectedObj {
  def main(args: Array[String]): Unit = {
    val protectedContainer = new SubProtectedContainer()
    protectedContainer.showXXX    
  }
}


class ProtectedContainer{
  /**
   * 这个方法是可以被子类调用的,这是private method 做不到的。
   */
  protected def protectedMethod = {
    println("This is a protected method of class ProtectedContainer")
  }
}
class SubProtectedContainer extends ProtectedContainer{
  def showXXX = {
    //调用父类的方法
    super.protectedMethod
  }
}

scala private private[package] protected 使用说明

标签:scala   private   protected   

原文地址:http://blog.csdn.net/hi_1234567/article/details/43155811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!