Say you have three printers that you need to write drivers for, Lexmark, Canon, and HP.
All three printers will have the print() and getSystemResource() methods.
However, print() will be different for each printer, and getSystemResource() remains the same for all three printers. You also have another concern, you would like to apply polymorphism.
Since getSystemResource() is the same for all three printers, you can push this up to the super class to be implemented, and let the subclasses implement print(). In Java, this is done by making print() abstract in the super class. Note: when making a method abstract in a class, the class itself needs to be abstract as well.
public abstract class Printer{
public void getSystemResource(){
// real implementation of getting system resources
}
public abstract void print();
}
public class Canon extends Printer{
public void print(){
// here you will provide the implementation of print pertaining to Canon
}
}
public class HP extends Printer{
public void print(){
// here you will provide the implementation of print pertaining to HP
}
}
public class Lexmark extends Printer{
public void print(){
// here you will provide the implementation of print pertaining to Lexmark
}
}
Notice that HP, Canon and Lexmark classes do not provide the implementation of getSystemResource().
Finally, in your main class, you can do the following:
public static void main(String args[]){
Printer printer = new HP();
printer.getSystemResource();
printer.print();
}