interface
definitions and abstract
Classes
public class Text2File {
private final PrintStream out;
public Text2File(final String fileName)
throws FileNotFoundException {
out = new PrintStream(new File(fileName));}
public void println(final String s) {
out.println(s);}
public void closeFile() {
out.close();}
}
|
File
Some dumb text More dumb text |
-
Missing
output.closeFile()
call.Some text portion may not be flushed to disk.
-
Calling
output.println(...)
afteroutput.closeFile()
:output.closeFile(); output.println("Too late!");
Last call will be silently ignored.
|
Compile time error: Required: java.lang.AutoCloseable Found: de.hdm_stuttgart.mi.sd1.Text2File |
accessModifier interface interfaceName [throwsClause]?{
[field]*
[method]*
}
AutoCloseable
promise
|
|
|
|
|
-
Java™ disallows multiple inheritance.
-
A class may implement an arbitrary number of interfaces:
public class X implements I1, I2, I3 {...}
/**
* Support auto-closing of resources
*/
public interface MyAutoCloseable {
/**
* close resource in question. Example: Terminate
* a database connection or a file stream.
*/
public void close();
}
/**
* Flush pending values.
*/
public interface MyFlushable extends MyAutoCloseable {
/**
* Save pending i.e. buffered values.
*/
public void flush();
}
public class Text2FileFlushable implements MyFlushable {
private PrintStream out;
...
/**
* Flushing pending output to underlying file.
*/
public void flush(){
out.flush();
}
/**
* Closing file thereby flushing buffer. Caution: Further calls
* to {@link #println(String)} will fail!.
*/
public void close() {
out.close();
out = null;
}
}