Tuesday 6 December 2016

Chapter 8.3 : Abstract Methods


If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.
The abstract keyword is also used to declare a method as abstract. An abstract method consists of a method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:
public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   
   public abstract double computePay();
   
   //Remainder of class definition
}
Declaring a method as abstract has two results:
·         The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.
·         Any child class must either override the abstract method or declare itself abstract.
A child class that inherits an abstract method must override it. If they do not, they must be abstract and any of their children must override it.
Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.
If Salary is extending Employee class, then it is required to implement computePay() method as follows:
/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; // Annual salary
  
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
 
   //Remainder of class definition
}







No comments:

Post a Comment