java8接口部分新特性

概述:

java8的接口,加入了static和default的支持,以下是对这两个特性的理解及测试。

 

一、测试代码

1. Animal接口

public interface Animal {

    static String run() {
        return "4条腿跑";
    }

    default String eat(Integer number) {
        return number + "玩命吃";
    }
}

该接口中的方法和Human接口的run方法和eat方法一样。

2. Human接口

public interface Human {

    static String run() {
        return "2条腿跑";
    }

    default String eat(Integer number) {
        return number + "想吃就吃";
    }
}

3. WhiteMan抽象类

public abstract class WhiteMan implements Animal {

    public String eat(Integer number) {
        return "我是白人" + number;
    }
}

4. CombinationOne类

public class CombinationOne extends WhiteMan {
    public static String run() {
        return "我1,不跑";;
    }

    @Override
    public String eat(Integer number) {
        return "我不想吃" + number;
    }
}

5. CombinationTwo类

public class CombinationTwo extends WhiteMan {
    public static String run() {
        return "我2,不跑";
    }
}

6.CombinationThree类

public class CombinationThree implements Animal, Human {
    @Override
    public String eat(Integer number) {
        return "我3,不跑" + number;
    }
}

二、测试

1. 实现类实现了抽象类和接口中的方法

——也就是说,CombinationOne实现了eat(String number)方法,而抽象类WhiteMan和接口Animal中也有该方法。

测试代码:

public class Main {
    public static void main(String[] args) {
        Animal combination = new CombinationOne();
        System.out.println(combination.eat(3));
    }
}

结果:

总结:

由于多态的原因,最后调用的是CombinationOne中的eat方法。

2. 实现类没有实现抽象类和接口中的方法。

测试代码:

public class Main {
    public static void main(String[] args) {
        Animal combination = new CombinationTwo();
        System.out.println(combination.eat(3));
    }
}

结果:

总结:

虽然CombinationTwo中没有实现eat方法,但是由于抽象类WhiteMan中实现了eat方法,所以也能调用到eat方法。

还有另外两种情况:

2.1. 第一种情况

假设:WhiteMan的eat改为抽象方法,即:

public abstract class WhiteMan implements Animal {
    public abstract String eat(Integer number);
}

此时,如果CombinationTwo继承了WhiteMan而没有实现eat方法,将会报错

2.2. 第二种情况

假设:WhiteMan的eat改为抽象方法,即:

public abstract class WhiteMan implements Animal {
}

此时,如果CombinationTwo继承了WhiteMan而没有实现eat方法,也不会报错,因为Animal的eat方法有默认方法体。

3. 实现的接口中,具有同名的方法

——Animal接口和Human接口中都有eat方法

测试代码:

public class Main {
    public static void main(String[] args) {
        Animal combination = new CombinationThree();
        System.out.println(combination.eat(3));
    }
}

测试结果:

总结:

CombinationThree类实现了Animal和Human两个接口,如下:

public class CombinationThree implements Animal, Human

由于Animal和Human接口中都有eat方法,因此,CombinationThree必须要重写eat方法,否则报错。而且,不论两个接口中的eat方法是否具有default方法体,都需要重写。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值