scala抽象类

抽象类

e383e09e-89e7-4c05-a95a-336abde5b6ed

trait
可以理解为可以带有具体方法实现的接口类

  1. trait Logger{ //trait相当于接口
  2. def log(msg:String){
  3. prinln("log " + msg)
  4. }
  5. }
  6. class Test extends Logger{
  7. def test{
  8. log("xxx")
  9. }
  10. }
  11. //使用
  12. object Basic3 extends App{
  13. val t = new Test //产生一个对象
  14. t.test //调用对象的方法
  15. }

含有抽象方法的trait

  1. trait Logger{
  2. def log(msf : String) //抽象方法
  3. }
  4. trait ConsoleLogger extends Logger{
  5. def log(msg : String){
  6. println(msg)
  7. }
  8. }
  9. class Test extends ConsoleLogger{
  10. def test{
  11. log("PPP")
  12. }
  13. }
  1. //使用
  2. object Basic3 extends App{
  3. val t = new Test
  4. t.test
  5. }
  6.  

抽象类和trait类(接口类)

  1. trait ConsoleLogger{
  2. def log(msg: String){
  3. println("save money : "+ msg)
  4. }
  5. }
  6. trait MessageLogger extends ConsoleLogger{
  7. override def log(msg:String){
  8.    println("save money to bank:" + msg)
  9. }
  10. }
  11. abstract class Account{
  12. def save
  13. }
  14. class MyAccount extends Account with ConsoleLogger{
  15. def save{
  16. log("100")
  17. }
  18. }
  19. //使用
  20. object Basic3 extends App{
  21.   val acc = new MyAccount with MessageLogger //定义一个带有特质的对象,trait为特质的意思,用with表示带有什么特质
  22. acc.save
  23. }

在object中使用apply方法

  1. class ApplyTest{
  2. def test{
  3. println("test")
  4. }
  5. }
  6. object ApplyTest{ //在object中定义的方法相当一静态方法
  7. def apply() = new ApplyTest
  8. def fun1{
  9. println("this is a static method")
  10. }
  11. }
  12. //类的框架
  13. class Basic4{
  14. }
  15. object Basic4 extends App{
  16. val a = ApplyTest() //注意,等号右边没有new关键字,调用ApplyTest对象时实际调用的是ApplyTest对象中的apply方法,然后把apply的返回值给a
  17. a.test
  18. }
  19. //结果输出为
  20. test

在class中使用apply方法

  1. class ApplyTest{
  2. def apply() = "APPLY"
  3. def test{
  4. println("test")
  5. }
  6. }
  7. object ApplyTest{
  8. def apply() = new ApplyTest
  9. def fun1{
  10. println("this is a static function")
  11. }
  12. }
  13. class Basic4{
  14. }
  15. object Basic4 extends App{
  16. val t = new ApplyTest
  17. println(t()) //t()表示调用t对象中的apply方法
  18. }

总结:

类名加括号调用的是object中的apply方法 ,如 val a = ApplyTest()

对象名加括号调用的是类中的apply方法,       如 t()

在一个代码块中导入包,出了这个快,就不起作用了

  1. {
  2. import xx.xxx.xyz
  3. }

重命名引入成员

  1. //例如,将util包中的hashMap类重命名为JavaHashMap
  2. import java.util.(HashMap => JavaHashMap)

隐藏

  1. //例如隐藏HashMap
  2. HashMap => _

自动引入

  1. //例如,引入java.lang中的所有类
  2. java.lang._
原文地址:https://www.cnblogs.com/wyhuang/p/3918605.html