Java8 中接口新增了default和static方法,这两种方法在接口中都可以有具体实现。
普通的抽象方法和default方法会被子类继承,子类必现实现普通抽象方法,而default方法子类可以实现,也可以选择不实现。
static方法不能被继承,也不能被子类实现,只能被自身调用
1.定义一个接口
定义一个璃月角色攻击模式的接口, 重击和普通攻击有固定倍率,而大招伤害因为每个角色不同,需要单独结算。而滑翔技能因为没有伤害,所以不需要继承实现,于是使用了静态方法
/**
* 璃月地区角色攻击方式及倍率接口
*/
public interface LiYue {
/**
* 元素爆发技能,每个角色的计算方式不同,需要具体实现
* @param atk 攻击力
* @return 伤害
*/
Integer elementalBurst(int atk);
/**
* 重击,,默认倍率 100%
* @param atk 攻击力
* @return 伤害
*/
default Integer thump(int atk) {
return new Double(Math.floor(atk * 2)).intValue();
}
/**
* 普通攻击,默认倍率 50%
* @param atk 攻击力
* @return 伤害
*/
default Integer attack(int atk) {
return new Double(Math.floor(atk * 1.5)).intValue();
}
/**
* 滑翔操作,没有伤害
*/
static void gliding(String name) {
System.out.println(name + "滑翔");
}
}
2.继承接口的类
- 1.第一个角色是刻晴,她的重击和普通攻击是固定倍率,只需要实现大招。
/**
* 刻晴
*/
public class KeQing implements LiYue {
/**
* 元素爆发技能,倍率 1000%
* @param atk 攻击力
* @return 伤害
*/
@Override
public Integer elementalBurst(int atk) {
return atk * 10;
}
}
- 2.而胡桃作为版本之子,她的重击和普通攻击和其他人不一样,所有技能都要实现
/**
* 胡桃
*/
public class HuTao implements LiYue {
@Override
public Integer elementalBurst(int atk) {
return atk * 20;
}
@Override
public Integer thump(int atk) {
return atk * 4;
}
@Override
public Integer attack(int atk) {
return atk * 2;
}
}
3.测试
进行一次打Boss 测试
public class TestBoss {
static int atk = 1700;
static void keQingSub() {
KeQing keQing = new KeQing();
LiYue.gliding("刻晴");
int damage = keQing.attack(atk) * 3 + keQing.thump(atk) + keQing.elementalBurst(atk);
System.out.println("刻晴的伤害总值:" + damage);
}
static void huTaoSub() {
HuTao huTao = new HuTao();
LiYue.gliding("胡桃");
int damage = huTao.attack(atk) * 3 + huTao.thump(atk) + huTao.elementalBurst(atk);
System.out.println("刻晴的伤害总值:" + damage);
}
public static void main(String[] args) {
keQingSub();
huTaoSub();
}
}
输出:
刻晴滑翔
刻晴的伤害总值:28050
胡桃滑翔
刻晴的伤害总值:51000
结论,胡桃的伤害比刻晴高!