大数据全系列 教程
1869个小节阅读:467.2k
目录
408考研
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
5.4.4 原理
特质特征原理,查看源码:
xxxxxxxxxx
public interface ProductDao {
int insert(final TraitDemo2.ProductVo pv);
boolean update(final TraitDemo2.ProductVo pv);
}
public static class ProductDaoImpl implements TraitDemo2.ProductDao {
//......
}
特征不就是接口吗?马丁为何费了半天劲,饶了一圈而不直接使用接口呢?
这是因为java中的接口是不能继承类的,它只能继承别的接口;但是在scala中特征却可以继承类。
xxxxxxxxxx
package com.itbaizhan.chapter05
object TraitDemo3 {
//特征继承一个类,可以实现让它所有的实现类都继承该类
trait ProductDao extends Exception{
def insert():Unit
def update():Unit
}
class ProductDaoImpl extends ProductDao{
override def insert(): Unit = ???
override def update(): Unit = ???
}
def main(args: Array[String]): Unit = {
val productDao = new ProductDaoImpl()
}
}
查看源码:
xxxxxxxxxx
public interface ProductDao {
void insert();
void update();
}
public static class ProductDaoImpl extends Exception implements TraitDemo3.ProductDao {
//......
}
扩展
xxxxxxxxxx
package com.itbaizhan.chapter05
import com.itbaizhan.chapter04.Animal
object TraitDemo3 {
//......
/**如下编写,运行时出现如下异常:Animal不是Exception的子类
* illegal inheritance; superclass Animal
is not a subclass of the superclass Exception
of the mixin trait ProductDao*/
/*class ProductDaoImpl2 extends Animal with ProductDao{
override def insert(): Unit = ???
override def update(): Unit = ???
}*/
//可将特征理解为接口和抽象类的结合体,scala中特征的使用要比抽象类多的多。
//特征也可以有伴生对象
object ProductDao{}
def main(args: Array[String]): Unit = {
//val productDao = new ProductDaoImpl()
val productDao2 = new ProductDaoImpl2()
}
}