CLASSES
Examples of Method Declarations
8.4.8
pos = 0;
}
}
class LineBufferOutput extends BufferOutput {
LineBufferOutput(OutputStream o) { super(o); }
public void putchar(char c) throws IOException {
super.putchar(c);
if (c == \n )
flush();
}
}
class Test {
public static void main(String[] args)
throws IOException
{
LineBufferOutput lbo =
new LineBufferOutput(System.out);
lbo.putstr("lbo\nlbo");
System.out.print("print\n");
lbo.putstr("\n");
}
}
This example produces the output:
lbo
print
lbo
The class
BufferOutput
implements a very simple buffered version of an
OutputStream
, flushing the output when the buffer is full or
flush
is invoked.
The subclass
LineBufferOutput
declares only a constructor and a single method
putchar
, which overrides the method
putchar
of
BufferOutput
. It inherits the
methods
putstr
and
flush
from class
Buffer
.
In the
putchar
method of a
LineBufferOutput
object, if the character argu
ment is a newline, then it invokes the
flush
method. The critical point about over
riding in this example is that the method
putstr
, which is declared in class
BufferOutput
, invokes the
putchar
method defined by the current object
this
,
which is not necessarily the
putchar
method declared in class
BufferOutput
.
Thus, when
putstr
is invoked in
main
using the
LineBufferOutput
object
lbo
, the invocation of
putchar
in the body of the
putstr
method is an invocation
of the
putchar
of the object
lbo
, the overriding declaration of
putchar
that
checks for a newline. This allows a subclass of
BufferOutput
to change the
behavior of the
putstr
method without redefining it.
173
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved