Using Exceptions with Abstract Classes

     

A common question regarding abstract classes is how to use exceptions with their method declarations. What exceptions can an inheriting method throw with respect to the inherited method? Consider the following class, whose single method throws one exception: IOException .

 

 public abstract class AbstractPrinter { abstract void printMessage(String msg) throws IOException; } 

The implementation of this abstract class is shown in PrinterImp1.java. To implement an abstract class, you simply extend it, just as you would extend any other class, using the extends keyword.

PrinterImpl.java

 

 package net.javagarage.demo.abstractclasses; import java.io.IOException; public class PrinterImpl extends AbstractPrinter {    void printMessage(String m) throws IOException {       System.out.println("Your message:            " + m);    } } 

graphics/fridge_icon.jpg

FRIDGE

This is different than in C#, in which classes are extended using the : operator. That is the same way that interfaces are implemented in that language. To implement an interface in Java, you use the keyword extends .


The preceding shows that the rules are the same as when you extend a regular class.

  • You cannot declare that your implementation method throws an exception if the superclass method does not.

  • If your abstract method declares that it throws an exception, your implementation method must throw that same exception, or any subclass of that exception.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net