Java接口和继承例子

来源:互联网 发布:606写卡器安装软件 编辑:程序博客网 时间:2024/06/07 23:16
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() {}//此方法仍需定义}

0 0
原创粉丝点击