| |
接口定义 关于java的接口定义方式,以下三种情况下可以采用接口定义方式: 1. 接口中声明的变量全部为final 和static类型的,并且这个接口的作用在于定义一些值不能改变的变量。 举个例子: public interface objectconstants{ public static final string space = new string(" "); public static final char formfeed = '/f'; } 2. 接口中只定义可供实现的抽象方法 eventlistener.java public interface eventlistener { public void handleevent(event evt); } runnable.java package java.lang; public interface runnable { public abstract void run(); } 3. 还有一种方式是上述两种方式的组合,如非必要一般会将这样一个接口定义拆分成两个接口定义 抽象类的定义 1. 如果一个类包含一个接口但是不完全实现接口定义的方法,那么该类必须定义成abstract型 例如inputstream.java类的定义方式: package java.io; public abstract class inputstream implements closeable { // skip_buffer_size is used to determine the size of skipbuffer private static final int skip_buffer_size = 2048; // skipbuffer is initialized in skip(long), if needed. private static byte[] skipbuffer; public abstract int read() throws ioexception;
public int read(byte b[]) throws ioexception { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws ioexception { if (b == null) { throw new nullpointerexception(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new indexoutofboundsexception(); } else if (len == 0) { return 0; } int c = read(); if (c == -1) { return -1; } b[off] = (byte)c; int i = 1; try { for (; i < len ; i++) { c = read(); if (c == -1) { break; } if (b != null) { b[off + i] = (byte)c; } } } catch (ioexception ee) { } return i; } public long skip(long n) throws ioexception { long remaining = n; int nr; if (skipbuffer == null) skipbuffer = new byte[skip_buffer_size]; byte[] localskipbuffer = skipbuffer; if (n <= 0) { return 0; } while (remaining > 0) { nr = read(localskipbuffer, 0, (int) math.min(skip_buffer_size, remaining)); if (nr < 0) { break; } remaining -= nr; } return n - remaining; } public int available() throws ioexception { return 0; } public void close() throws ioexception {} public synchronized void mark(int readlimit) {} public synchronized void reset() throws ioexception { throw new ioexception("mark/reset not supported"); } public boolean marksupported() { return false; } } 2. 抽象类的方法体中只定义抽象的方法,例如abstractmethoderror.java package java.lang; public class abstractmethoderror extends incompatibleclasschangeerror { public abstractmethoderror() { super();} public abstractmethoderror(string s) { super(s); } }
|
|