文章标题

来源:互联网 发布:linux samba 端口修改 编辑:程序博客网 时间:2024/05/19 22:52

父类接口实现子类多态的引用

当我们定义了一个类 想让这个类实现扩展功能时 可以考虑用接口(父类)来实现此功能 注意 用接口实现的前提是所有扩展功能都应该具有相同的特点 而真正的对实现扩展功能的类是不真正必要该功能

如何实现呢》?

我们将这些功能的特性进行类似封装,成为这些新功能的父接口 然后在创建若干个类来实现接口 最后 在原有类中定义得到该接口的方法。将若干个功能类的对象作为实参 将借口型引用变量作为形参进行程序的设计
例如

interface Zong{
void open();
void close();
}

public class Iftozilei {
void begin() {
System.out.println(“gameplay”);}
public void useZong(Zong n) {
n.open();
n.close();
System.out.println(“game en
d”);
}

}
public class ShengKa implements Zong {
public void open () {
System.out.println(“gamenumber4”);
}
public void close() {
System.out.println(}}}}
gamenumber5”);
}
}public class WangKa implements Zong{
public void open() {
System.out.println(“gamenuber2”);
}
public void close() {
System.out.p}
intln(“gamenumber3”);
}
}public class ShiXian {
public static void main(String[] args) {

Iftozilei i=new Iftozilei();
i.useZong(new WangKa());
}
}

原创粉丝点击