Witscale Test Center

3.5 Method declaration and modifiers > 3.5.1 Abstract methods


3.5.1 Abstract methods

When you apply the abstract modifier to a method, it becomes an abstract method which means a method without any implementation. Declaration of such method has only the method signature followed by semicolon. In our earlier discussion of abstraction (see section 3.3.1 ) we have seen why you would want to have such methods in the class. Here we will see another example to better understand implementation of the abstract methods. Figure3.6 illustrates an abstract class Shape that has two abstract methods draw() and erase().Figure also shows subclasses of class Shape; two concrete subclasses- Circle and Line and one abstract subclass Polygon. Note that concrete subclasses means they should not have any abstract behavior. Hence they must implement the abstract methods draw() and erase(). But since the class Polygon is declared as abstract, it need not implement the abstract methods. Note however that Polygon’s concrete subclasses must provide implementation for these two abstract methods.

 

 


 Figure 3.6 Abstract method declaration and its implementations

 

Thus, it is ensured that the abstract methods are eventually implemented by subclasses. In this example, declaring abstract methods draw() and erase() in class Shape ensures that every shape object is draw-able and erasable irrespective of whether it is a Circle, Line or Polygon object. As we have seen earlier, an abstract class may provide implementation for some common behavior in concrete methods. The abstract class Shape has one such concrete method moveTo(), this method is inherited and hence it is shared among the subclasses.

Declaration facts for abstract method

You might have noticed that the syntax of abstract method declaration is different from the regular methods. However, there is more to it than just the declaration difference. Following are the additional rules you need to follow while declaring the abstract methods.

§         Any class that contains abstract methods must be an abstract class. Otherwise, a compile-time error is thrown. Every subclass of an abstract class must provide an implementation for all the abstract methods. If not, the subclass must declare itself as abstract and defer the implementation to it subclasses.  

There is a good reason why any class that contains abstract methods must be an abstract class. Since abstract classes cannot be instantiated. This rule makes sure that the subclass of an abstract class is usable only when it implements the abstract behavior.

 

         Abstract method implies that its implementation lies in the subclasses, but declaring abstract methods as private or final (we will soon see the final methods) prevents overriding and hence makes it impossible to provide any implementation in subclasses. Therefore, compiler does not allow abstract method to be private or final.