">
快速掌握接口和抽象类的定义方式
发布时间: 2008-2-18 13:53 作者: 未知 来源: 网络转载

 
 
接口定义

  关于java的接口定义方式,以下三种情况下可以采用接口定义方式:

◆接口中声明的变量全部为fnal 和statc类型的,并且这个接口的作用在于定义一些值不能改变的变量。

举个例子:


publc nterface ObjectConstants{
publc statc fnal Strng SPACE = new Strng(" ");
publc statc fnal char FORMFEED = '\f';
}

◆接口中只定义可供实现的抽象方法


EventLstener.java
publc nterface EventLstener {
publc vod handleEvent(Event evt);
}
Runnable.java
package java.lang;
publc nterface Runnable {
publc abstract vod run();
}

◆还有一种方式是上述两种方式的组合,如非必要一般会将这样一个接口定义拆分成两个接口定义

抽象类的定义

1.如果一个类包含一个接口但是不完全实现接口定义的方法,那么该类必须定义成abstract型

例如nputStream.java类的定义方式:


package java.o;
publc abstract class nputStream mplements Closeable {
// SKP_BUFFER_size s used to determne the size of skpBuffer
prvate statc fnal nt SKP_BUFFER_size = 2048;
// skpBuffer s ntalzed n skp(long), f needed.
prvate statc byte[] skpBuffer;
publc abstract nt read() throws OExcepton;


publc nt read(byte b[]) throws OExcepton {
return read(b, 0, b.length);
}
publc nt read(byte b[], nt off, nt len) throws OExcepton {
f (b == null) {
throw new NullPonterExcepton();
} else f ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new indexOutOfBoundsExcepton();
} else f (len == 0) {
return 0;
}
nt c = read();
f (c == -1) {
return -1;
}
b[off] = (byte)c;
nt = 1;
try {
for (; < len ; ++) {
c = read();
f (c == -1) {
break;
}
f (b != null) {
b[off + ] = (byte)c;
}
}
} catch (OExcepton ee) {
}
return ;
}
publc long skp(long n) throws OExcepton {
long remanng = n;
nt nr;
f (skpBuffer == null)
skpBuffer = new byte[SKP_BUFFER_size];
byte[] localSkpBuffer = skpBuffer;
f (n <= 0) {
return 0;
}
whle (remanng > 0) {
nr = read(localSkpBuffer, 0,
(nt) Math.mn(SKP_BUFFER_size, remanng));
f (nr < 0) {
break;
}
remanng -= nr;
}
return n - remanng;
}
publc nt avalable() throws OExcepton {
return 0;
}
publc vod close() throws OExcepton {}
publc synchronzed vod mark(nt readlmt) {}
publc synchronzed vod reset() throws OExcepton {
throw new OExcepton("mark/reset not supported");
}
publc boolean markSupported() {
return false;
}
}

2.抽象类的方法体中只定义抽象的方法,例如AbstractMethodError.java


package java.lang;
publc class AbstractMethodError extends ncompatbleClassChangeError {
publc AbstractMethodError() {
super();}
publc AbstractMethodError(Strng s) {
super(s); }
} 

 

相关链接:软件测试

打印】【关闭窗口