都知道抽象类可以没有抽象方法,这时的抽象类和普通类的最大差别就是不能实例化.一直没找到在什么环境下用到这种特殊的抽象类.最近看了jdk的I/O包后,发现里面有个很好的例子,就是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就是一个没有抽象方法的抽象类,里面的每个方法都是调用构造函数传入的Reader对象的方法.这种抽象类你不能实例化它,因为实例化它没意义,它还没实现任何Filter的功能.在extends具体子类时实现Filter功能,实例化相应的子类才有实际意义.
我们可以写FilterReader的一个具体子类如下:
/**
* FilterReader是一个抽象类,不能实例化该类,FilterReader类的每个方法都是实现的,
* 里面调用的都是FilterReader(Reader in)的传入参数in的方法.
*/
public
class
UppercaseConvertor
extends
FilterReader
{
// 构造方法由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);
}
}
}