|
Re: difference between class and interface
|
Posted: Mar 28, 2007 12:52 AM
|
|
A interface defines, which method a class has to implement. This way - if you want to call a method defined by an interface - you don't need to know the exact class type of an object, you only need to know that it implements a specific interface.
Example:
interface Printer {
public void print(String text);
}
class FilePrinter implements Printer {
public void print(String text) {
//append the text to a file
}
}
class ScreenPrinter implements Printer {
public void print(String text) {
//write the text on the screen
}
}
class SomeClass {
public printSomething(Printer myPrinter) {
myPrinter.print("Hello");
}
}
If you call SomeClass.printSomething(...) it does not matter if you pass an instance of FilePrinter or ScreenPrinter, because the method just does not care. It knows that the object implements the interface Printer and also implements it's methods.
Another important point about interfaces is that a class can implement multiple interfaces.
|
|