kewin1983的个人博客分享 http://blog.sciencenet.cn/u/kewin1983

博文

java中接口interface

已有 8005 次阅读 2013-3-12 14:11 |系统分类:科研笔记| Interface, java, 接口

JAVA的接口最大的作用就是统一:统一函数形式、调用方式,保证函数的进出都可以一致。
 
1、多态接口动态加载
配合Class.forName().newInstance(),可以完成以函数为主的程序,这些函数可以统一入口参数。
接口中只写函数形式,具体实现则要到类中写:
//Common.java
public interface Common {
double runTimer(double a, double b, double c);
}
//Car中实现这个接口a*b/c
public class Car implements Common {
public double runTimer(double a, double b, double c) {
return ( a*b/c );
}
}
//Plane中实现这个接口a+b+c
public class Plane implements Common {
public double runTimer(double a, double b, double c) {
return (a+ b + c);
}
调用时则可以统一命名和调用
Common d=(Common) Class.forName("Car").newInstance();
v=d.runTimer(A,B,C);
 
2、接口作为方法的参数传递
可以将接口类型的参数作为方法参数,在实际使用时可以将实现了接口的类传递给方法,后方法或按照重写的原则执行,实际调用的是实现类中的方法代码体,这样便根据传进屋的参数的不同而实现不同的功能。
 
interface Extendbroadable{
public void inPut();
}
 
class KeyBroad     implements Extendbroadable{
public void inPut(){
System.out.println("n hi,keybroad has be input into then mainbroad!n");
}
}
class NetCardBroad     implements Extendbroadable{
public void inPut(){
System.out.println("n hi,netCardBroad has be input into then mainbroad!n");
}
}
//上面完成了一个接口,分别实现,接下来就是统一调用
class CheckBroad{
public void getMainMessage(Extendbroadable ext){
ext.inPut();
}
}
具体使用
KeyBroad kb=new KeyBroad();
NetCardBroad ncb=new NetCardBroad();
CheckBroad cb=new CheckBroad();
cb.getMainMessage(kb);
cb.getMainMessage(ncb);


 


https://blog.sciencenet.cn/blog-384997-669585.html

上一篇:JAVA matlab
下一篇:JAVA的抽象类
收藏 IP: 60.10.24.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-9-27 19:27

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部