都知道抽象類可以沒有抽象方法,這時的抽象類和普通類的最大差別就是不能實例化.一直沒找到在什么環(huán)境下用到這種特殊的抽象類.最近看了jdk的I/O包后,發(fā)現(xiàn)里面有個很好的例子,就是FilterReader類.以下是FilterReader的代碼: public abstract class FilterReader extends Reader ...{ /** *//** * The underlying character-input stream. */ protected Reader in; /** *//** * Create a new filtered reader. * * @param in a Reader object providing the underlying stream. * @throws NullPointerException if <code>in</code> is <code>null</code> */ protected FilterReader(Reader in) ...{ super(in); this.in = in; } /** *//** * Read a single character. * * @exception IOException If an I/O error occurs */ public int read() throws IOException ...{ return in.read(); } /** *//** * Read characters into a portion of an array. * * @exception IOException If an I/O error occurs */ public int read(char cbuf[], int off, int len) throws IOException ...{ return in.read(cbuf, off, len); } /** *//** * Skip characters. * * @exception IOException If an I/O error occurs */ public long skip(long n) throws IOException ...{ return in.skip(n); } /** *//** * Tell whether this stream is ready to be read. * * @exception IOException If an I/O error occurs */ public boolean ready() throws IOException ...{ return in.ready(); } /** *//** * Tell whether this stream supports the mark() operation. */ public boolean markSupported() ...{ return in.markSupported(); } /** *//** * Mark the present position in the stream. * * @exception IOException If an I/O error occurs */ public void mark(int readAheadLimit) throws IOException ...{ in.mark(readAheadLimit); } /** *//** * Reset the stream. * * @exception IOException If an I/O error occurs */ public void reset() throws IOException ...{ in.reset(); } /** *//** * Close the stream. * * @exception IOException If an I/O error occurs */ public void close() throws IOException ...{ in.close(); } } 可以看到FilterReader就是一個沒有抽象方法的抽象類,里面的每個方法都是調(diào)用構(gòu)造函數(shù)傳入的Reader對象的方法.這種抽象類你不能實例化它,因為實例化它沒意義,它還沒實現(xiàn)任何Filter的功能.在extends具體子類時實現(xiàn)Filter功能,實例化相應(yīng)的子類才有實際意義. 我們可以寫FilterReader的一個具體子類如下: /** *//** * FilterReader是一個抽象類,不能實例化該類,FilterReader類的每個方法都是實現(xiàn)的, * 里面調(diào)用的都是FilterReader(Reader in)的傳入?yún)?shù)in的方法. */ public class UppercaseConvertor extends FilterReader...{ // 構(gòu)造方法由FilterReader的protected上升到public的 public UppercaseConvertor(Reader in) ...{ super(in); } @Override public int read() throws IOException...{ int c = super.read(); return (-1==c?c:Character.toUpperCase((char)c)); } @Override public int read(char[] buf,int offset, int count) throws IOException...{ int nread = super.read(buf, offset, count); int last = offset + nread; for(int i=0;i<last;i++) buf[i] = Character.toUpperCase(buf[i]); return nread; } public static void main(String[] args) throws IOException ...{ UppercaseConvertor uc = new UppercaseConvertor(new FileReader("d:\log.txt")); BufferedReader br = new BufferedReader(uc); String r; while(null!=(r=br.readLine()))...{ System.out.println(r); } } } |
|