首页 > 其他 > 详细

内部类

时间:2019-09-02 00:56:55      阅读:77      评论:0      收藏:0      [点我收藏+]

内部类

package base

// App重写了main方法 可以直接运行IClass
object IClass extends App {

  //调用外部类中的内部类对象
  val ic1 = new OuterClass().InnerObject
  println("y = " + ic1.y)

  // 创建外部类实例
  val oc = new OuterClass()
  // 通过外部类实例创建内部类实例
  val ic2 = new oc.InnerClass()
  println("x = " + ic2.x)

  // 通过方法获取内部类实例
  val ic3 = new OuterClass().getInnerClass
  println("x = " + ic3.x)

  // 通过外部类对象创建内部类实例
  val oic = new OuterObject.InnerClass()
  println("m = " + oic.m)

  // 通过外部类对象调用内部类对象
  println("n = " + OuterObject.InnerObject.n)

}

// 外部类
class OuterClass {

  // 封装返回InnerClass的实例方法
  def getInnerClass: InnerClass = {
    new InnerClass()
  }

  // 内部类
  class InnerClass {
    var x = 1
  }

  // object 里面的字段都类似于被 static修饰了
  object InnerObject {
    val y = 2
  }

}

// 外部对象
object OuterObject {

  // 内部类
  class InnerClass {
    var m = 3
  }

  // 内部对象
  object InnerObject {
    var n = 4
  }

}

匿名内部类

package base

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

    // 匿名内部类, 直接实现抽象方法
    val abs = new AbsC {
      override def fun(): String = {
        "Abs class fun!"
      }
    }
    println(abs.fun())

  }
}

// 抽象类
abstract class AbsC {
  // 抽象方法
  def fun():String
}

内部类

原文:https://www.cnblogs.com/studyNotesSL/p/11443815.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!