478 Object-Oriented Programming Chapter (Web site design and hosting) 9 Software Engineering Observation

478 Object-Oriented Programming Chapter 9 Software Engineering Observation 9.24 The ability to declare an abstract method gives the class designer considerable power over how subclasses will be implemented in a class hierarchy. Any new class that wants to inherit from this class is forced to override the abstract method (either directly or by inheriting from a class that has overridden the method). Otherwise, that new class will contain an abstract method and thus be an abstract class, unable to instantiate objects. Software Engineering Observation 9.25 An abstract can still have instance data and nonabstract methods subject to the normal rules of inheritance by subclasses. An abstract class can also have constructors. Common Programming Error 9.7 Attempting to instantiate an object of an abstract class (i.e., a class that contains one or more abstract methods) is a syntax error. Common Programming Error 9.8 It is a syntax error if a class with one or more abstract methods is not explicitly declared abstract. Let us consider the Employeeclass (Fig. 9.16). The publicmethods include a constructor that takes the first name and last name as arguments; a getFirstName method that returns the first name; a getLastName method that returns the last name; a toStringmethod that returns the first name and last name separated by a space; and an abstractmethod earnings. Why is this method abstract? The answer is that it does not make sense to provide an implementation of this method in the Employeeclass. We cannot calculate the earnings for a generic employee we must first know what kind of employee it is. By making this method abstract we are indicating that we will provide an implementation in each concrete subclass, but not in the superclass itself. 1 // Fig. 9.16: Employee.java 2 // Abstract base class Employee. 3 4 public abstract class Employee { 5 private String firstName; 6 private String lastName; 7 8 // constructor 9 public Employee( String first, String last ) 10 { 11 firstName = first; 12 lastName = last; 13 } 14 15 // get first name 16 public String getFirstName() 17 { 18 return firstName; 19 } 20 Fig. 9.16 Employeeabstractsuperclass (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Leave a Reply