本文共 893 字,大约阅读时间需要 2 分钟。
public interface Valuable {
public double getMoney();//接口中的方法只能是public类型
}
interface Protectable {
public void beProtected();
}
interface A extends Protectable { //接口之间可相互继承(A接口有两个方法 m(),beProtected())
void m();
}
abstract class Animal { //抽象类
private String name;
abstract void enjoy();//只声明了方法
}
class GoldenMonkey extends Animal implements Valuable, Protectable { //继承Animal类,并实现Valuable和Protectable接口
public double getMoney() {//重写接口Valuable的方法
return 10000;
}
public void beProtected() {//重写接口Protectable 的方法
System.out.println("live in the room");
}
public void enjoy() {}//重写抽象类Animal的方法
public void test() {
Valuable v = new GoldenMonkey();//OK,但只能看到Valuable中的方法
v.getMoney();
//强制转换为Protectable类,只能看到Protectable中的方法(相当于换了一个视角)
Protectable p = (Protectable)v;//强制类型转换
p.beProtected();
}
}
class Hen implements A {//需要定义两个接口的方法
public void m() {}
public void beProtected() {}//此方法仍需定义
}
转载地址:https://blog.csdn.net/weixin_33102135/article/details/114248128 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!