OOP FINALS that inherit from each other, you can ell which
is the base class and which is the derived class
MODULE 8 by using the two classes in a sentence with You are familiar with the concept of the phrase “is a(n).” A derived class always “is inheritance from all sorts of nonprogramming a” case or example of the more general base situations. When you use the term class. For example, a Tree class can be a base inheritance, you might think of genetic class to an Evergreen class. An Evergreen “is inheritance. You know from biology that your a” Tree, so Tree is the base class; however, it blood type and eye color are the product of is not true for all Trees that “a Tree is an inherited genes; many facts about you—your Evergreen.” Similarly, an attributes, or “data fields”—are inherited. EmployeeWithTerritory “is an” Employee— Similarly, you often can credit your behavior but not the other way around—so Employee to inheritance. For example, your attitude is the base class. toward saving money might be the same as You can write a statement that instantiates a your grandmother’s, and the odd way that derived class object, such as the following: you pull on your ear when you are tired might EmployeeWithTerritory northernRep = new match what your Uncle Steve does—thus, EmployeeWithTerritory(); your methods are inherited, too. You also might choose plants and animals based on Then you can use any of the next statements inheritance. You plant impatiens next to your to get field values for the northernRep object: house because of your shady location; you adopt a Doberman Pinscher because you need northernRep.getId(); a watchdog. Every individual plant and pet has northernRep.getSalary(); slightly different characteristics, but within a species, you can count on many consistent northernRep.getTerritory(); inherited attributes and behaviors. Similarly, The northernRep object has access to all the classes you create in object-oriented three get methods—two methods that it programming languages can inherit data and inherits from Employee and one method that methods from existing classes. In Java and all belongs to EmployeeWithTerritory. Similarly, object-oriented languages, inheritance after the northernRep object is declared, any • Save time because the Employee fields and of the following statements are legal: methods already exist northernRep.setId(915); • Reduce errors because the Employee northernRep.setSalary(210.00); methods already have been used and tested northernRep.setTerritory(5); • Reduce the amount of new learning The northernRep object has access to all the Inheritance Terminology parent Employee class set methods, as well as A class that is used as a basis for inheritance, its own class’s new set method. Inheritance is such as Employee, is a base class. When you a one-way proposition; a child inherits from a create a class that inherits from a base class parent, not the other way around. When you (such as EmployeeWithTerritory), it is a instantiate an Employee object, it does not derived class. When considering two classes have access to the EmployeeWithTerritory methods. It makes sense that a parent class MODULE 9 object does not have access to its child’s data and methods. When you create the parent Overriding Superclass Methods class, you do not know how many future When you create a subclass by extending an subclasses it might have or what their data existing class, the new subclass contains data fields or methods might look like. In addition, and methods that were defined in the original subclasses are more specific than the superclass. In other words, any child class superclass they extend. object has all the attributes of its parent. You can use the instanceof operator to Sometimes, however, the superclass data fields and methods are not entirely determine whether an object is a member or descendant of a class. For example, if appropriate for the subclass objects; in these cases, you want to override the parent class northernRep is an EmployeeWithTerritory object, the value of each of the following members. To override a field or method in a child class means to use the child’s version expressions is true: northernRep instanceof EmployeeWithTerritory northernRep instead of the parent’s version. When you use the English language, you often use the same instanceof Employee method name to indicate diverse meanings. If aClerk is an Employee object, the following For example, if you think of is true: MusicalInstrument as a class, you can think of play() as a method of that class. If you think of aClerk instanceof Employee various subclasses such as Guitar and Drum, However, the following is false: you know that you carry out the play() method quite differently for each subclass. aClerk instanceof EmployeeWithTerritory Using the same method name to indicate different implementations is called Programmers say that instanceof yields true if polymorphism, a term meaning many forms— the operand on the left can be upcast to the many different forms of action take place, operand on the right. even though you use the same word to Common Properties describe the action. In other words, many forms of the same action-describing word Below is a sample hierarchy with attribute and exist, depending on the associated object. method definitions Calling Constructors During Inheritance We can make the following observations about the class diagram: When you create any object, as in the following statement, you are calling a • attribute name and method getName() are constructor: SomeClass anObject = new common in all three classes; SomeClass(); When you instantiate an object that is a member of a subclass, you actually • attribute employee number and method are calling both the constructor for the base getEmployeeNumber() are common in class and the constructor for the extended, Employee and SalesPerson class; derived class. When you create any subclass • attribute commission is specific to object, the superclass constructor must SalesPerson class and does not appear in execute first, and then the subclass other classes. constructor executes. When a superclass contains a default overrides the superclass method. However, if constructor and you instantiate a subclass a method has been overridden but you want object, the execution of the superclass to use the superclass version within the constructor usually is transparent—that is, subclass, you can use the keyword super to nothing calls attention to the fact that the access the parent class method. superclass constructor is executing unless the constructor contains some action such as Comparing this and super displaying a message. However, you should realize that when you create a child object both the parent and child constructors execute.
Using Superclass Constructors that Require
Argument
When you do not provide a constructor for a
class, Java automatically supplies you with a default constructor—one that never requires Employing Information hiding arguments. When you write your own constructor, you replace the The Student class shown below is an example automaticallysupplied version. Depending on of a typical Java class. Within the Student your needs, a constructor you create for a class, as with most Java classes, the keyword class might be a default constructoror might private precedes each data field, and the require arguments. When a superclass has keyword public precedes each method. In only constructors that require arguments, you fact, the four get and set methods are public must be certain that any subclasses provide within the Student class specifically because the superclass constructor with the the data fields are private. Without the public arguments it needs. get and set methods, there would be no way to access the private data fields. When a superclass has a default constructor, you can create a subclass with or without its The concept of keeping data private is known own constructor. This is true whether the as information hiding. When you employ default superclass constructor is the information hiding, your data can be altered automatically supplied one or one you have only by the methods you choose and only in written. When a superclass contains only ways that you can control. For example, you constructors that require arguments; might want the setIdNum() method to check however, you must include at least one to make certain the idNum is within a specific constructor for each subclass you create range of values. If a class other than the Student class could alter idNum, idNum could Accessing Superclass Methods be assigned a value that the Student class Earlier in this chapter, you learned that a couldn’t control. subclass can contain a method with the same Methods You Cannot Override name and arguments (the same signature) as a method in its parent class. When this The three types of methods that you cannot happens and you use the method name with a override in a subclass are: subclass object, the subclass method • static methods
• final methods
• Methods within final classes
A Subclass Cannot Override static Methods in
Its Superclass
A subclass cannot override methods that are
declared static in the superclass. In other words, a subclass cannot override a class MODULE 10 method—a method you use without instantiating an object. A subclass can hide a Code Reuse, Making Changes in Class static method in the superclass by declaring a Hierarchy static method in the subclass with the same Code Reuse/ Making Changes in Class signature as the static method in the Hierarchy By allowing information of a superclass. Then, you can call the new static superclass to be taken on by subclasses, the method within the subclass or in another class information is said to be reused at the by using a subclass object. However, this subclass level. All newly created instances of static method that hides the superclass static the subclasses would have as part of their method cannot access the parent method definition the inherited information. using the super object. employee number, basic salary, and A Subclass Cannot Override final Methods in getEmployeeNumber() of the Employee class Its Superclass and name and getName() of the Person class are said to be reused by the Manager and Secretary.
Changes to software specification are
inevitable. Let us consider how changes in a class hierarchy impact software maintenance as a whole. The following situations will be discussed:
• Change in property definition for all
subclasses-Suppose a change in representational scheme of the employee number in Figure 6-3 is required. This change will affect not only the attribute employee A Subclass Cannot Override Methods in a number but also the method final Superclass getEmployeeNumber() and possibly other classes that inherit employee number. We will examine this change in two possibilities:
(a) Inheritance Is Not Available
In the case where inheritance is not available, the attribute employee number and method a manager—basic salary plus allowance; getEmployeeNumber() would have to be defined in all the relevant classes, a salesperson—basic salary plus for example, Employee, Manager, commission; SalesPerson and Secretary. The a secretary—basic salary; change in representational scheme of employee number would thus have to a technician—basic salary; be affected individually on these classes. The redundancy arising from a clerk—basic salary. the multiple definition of employee At the Employee class, a getPay() method is number and getEmployeeNumber() defined to return the monthly pay of an may lead to inconsistency in definition employee since the method applies to all if the change is not carried out classes of employee. properly. (b) Inheritance Is Available • Adding/deleting a class-Adding a class into an existing class hierarchy can be detrimental With inheritance, the situation is to the stability of the hierarchy. It is always different. We would first define attribute recommended that the addition of a new employee number and method class be created as a subclass in the class getEmployeeNumber() in Employee class hierarchy. The definition of existing classes and let subclasses Manager, SalesPerson will not be adversely affected by this and Secretary inherit these definitions approach. from Employee class. The required change in representational scheme for attribute MODULE 11 employee number would be limited to the Employee class. The change would be Creating and Using Interfaces-Some object- propagated to the subclasses via oriented programming languages, such as C+ inheritance. In this way, the change is +, allow a subclass to inherit from more than thus limited to the superclass, enabling a one parent class. uniform and consistent property Automobile class that contains data fields definition for all subclasses. In addition, such as vehicle identification number, make, redundancy in property definition at the model, and year. As well as Automobile subclass level can be minimized and information and methods. It would be software maintenance enhanced. convenient to inherit from both the • Change in property definition for some InsuredItem and Automobile classes. The subclasses- In some situations, a change in capability to inherit from more than one class property definition at the superclass level may is called multiple inheritance. not necessarily apply to all subclasses. The above solution would therefore not apply in these situations. To illustrate, let us extend the Person class hierarchy further to include two more employee classes: Technician and Multiple Inheritance Using Interface-The Clerk. Let us assume the following for a interface construct in Java is used with single HomeCare employee: inheritance to provide some form of multiple inheritance. MODULE 12 • All of the methods in an interface are implicitly public and abstract, and all of its Attributes in an Interface data items (if any) are implicitly public, static, Data attributes declared in an interface and final. construct are always static and final. They are • When a class inherits from another, the static as there can only be one copy of the child class can use the nonprivate, data available and final since they are not nonoverridden members of its parent’s class, modifiable. By declaring data attributes in an but when a class uses an interface, it must interface, constant declarations for use in implement its own version of each method methods is possible. MODULE 13 Methods in an Interface Polymorphism All methods in an interface are abstract methods and any class that uses the interface Up till now we have been assuming all code is must provide an implementation for them. bound during compilation. Such binding is Like data attributes, an interface does not known as static binding. Binding can also take have to explicitly declare its methods abstract place at run-time and this form of binding is using the keyword abstract. Similarly, known as dynamic binding. Static binding is interface methods are always public, and the limited and may lead to difficulty in software access modifier public keyword is not required maintenance. Dynamic binding, on the other since it is implied in the interface declaration. hand, provides design flexibility and may However, in contrast with data attributes in enhance software maintainability. In this an interface, methods may not be static since chapter, we will discuss static binding and static methods, being class specific, are never dynamic binding. We will also examine how abstract. dynamic binding contributes to polymorphism —the ability of objects to respond to the Abstract Class and Interface same message with the appropriate method A class implementing an interface must based on their class definition implement all the abstract methods declared Static Binding: adding a triangle in an interface; otherwise, the class is considered as an abstract class and must be in the data section where a triangle is declared using the abstract keyword defined;
in the main code section where the
detection of a triangle and the appropriate routine call have to be included in the switch
statement; and
in the routine section where the specific
routine for calculating the area of the triangle has to be included.
Multiple places are affected as a result of
Remember: extending shape types, and this is error prone. An alternative approach to static binding is of superclass references, it can hold subclass dynamic binding. references. This is true whether the superclass in question is abstract or concrete. More on Dynamic Method Binding Operation Overloading-Circle and Square When you create a superclass and one or have similar calculateArea() method in their more subclasses, each object of each subclass class definition. Although both methods have “is a” superclass object. Every the same method signature, they have SalariedEmployee “is an” Employee; every different method implementation, since the Dog “is an” Animal. (The opposite is not true. formula for calculating area of each is not the Superclass objects are not members of any of same. While it is impossible in conventional their subclasses. An Employee is not a imperative programming languages to have SalariedEmployee. An Animal is not a Dog.) two routines having the same name, it is Because every subclass object “is a” allowed in object-oriented programming. The superclass member, you can convert subclass ability to use the same name for two or more objects to superclass objects. As you are methods in a class is known as operation aware, when a superclass is abstract, you overloading in object-oriented terms cannot instantiate objects of the superclass; however, you can indirectly create a reference Same Method Signature-Two methods are to a superclass abstract object. A reference is said to have the same method signature if:the not an object, but it points to a memory name of the methods are the same; and the address. When you create a reference, you do number and type of formal parameters are not use the keyword new to create a concrete the same. object; instead, you create a variable name in which you can hold the memory address of a Overloading Method Names-Methods having the same method signature may pose concrete object. So, although a reference to an abstract superclass object is not concrete, problems in the compilation process depending on where they are used in the you can store a concrete subclass object reference there. program. In this section, we will consider various situations and report on the validity of Dynamic method binding-is most useful when overloaded method names. In the code you want to create a method that has one or fragment below, method A() is overloaded by more parameters that might be one of several A(int x), A(int x, int y), and A(String s). These types. four methods are distinguished in the compilation process by the number and type Creating arrays of Subclass Objects-Recall of parameters present in the method call. that every array element must be the same data type, which can be a primitive, built-in type, or can be a type based on a more complex class. When you create an array in Java, you are not constructing objects. Instead, you are creating space for references to objects. In other words, although it is convenient to refer to an array of objects, every array of objects is really an array of object references. When you create an array Polymorphism is facilitated by dynamic binding and the ability to use the same name for similar methods across class definitions. It would not be possible to achieve polymorphism if a programming language does not support these facilities. Polymorphism encourages programmers to specify what method should happen rather than how it should happen. This approach allows flexibility in code design and promotes incremental program development.
MODULE 14
Modularity-We have so far discussed the
Polymorphism (additionals)-We noted earlier basic facilities for creating objects through in that we can achieve code binding at run- Java class definitions and code reuse by time with dynamic binding. Also, appropriate inheriting properties of similar but more method call can be made without making any general classes. In this chapter, we look at the direct reference to it in the message. As is important issue of modularity and the related evident in the output of the code, the mechanisms available in Java. appropriate calculateArea() method for the respective object was selected. Methods and Classes as Program Units-A method is comprised of statement sequences It is apparent that the message and is often viewed as the smallest program (calculateArea()) from the sender (main()) has unit to be considered as a subprogram. It is been interpreted appropriately by the self-contained and designed for a particular receiver. A circle receiving the message has task which represents an object behavior. used its own method calculateArea() to Together with data, a coordinated set of calculate the area and a square receiving the methods completes the specification of same message has done the same with its objects. As we have seen, data and methods own calculateArea() method. The ability of are the constituents of a class definition. different objects to perform the appropriate Compared to a method, a class definition is method in response to the same message is the next bigger unit under design. Properties known as polymorphism in object-oriented defined in a class can be distinguished into object and class properties. Object properties programming. are definitions that are specific to objects and Selection of Method-In polymorphism, the apply to all objects from the same class. Class interpretation of a message is not affected by properties, on the other hand, apply only to a sender. What a sender knows is that an the class even though the structure and object can respond to a message but it does behavior of objects of a class is defined by the not know which class the object belongs to or class. how it will respond to the message. Object and Class Properties Incremental Development Counting Instance Listing 8-1 contains the code for an example that counts the number of objects instantiated from the SalesPerson class.
The variable count in the alternative solution
is declared as an object attribute rather than a local variable of the static method main() as was the case for the previous solution. As an The code begins with the declaration of a object attribute, count can now be variable count. This variable is used to incremented in the constructor method of the continually create the number of SalesPerson SalesPerson class. However, with each objects. For each creation of a SalesPerson obj instantiation of a SalesPerson object, the count variable of each newly created object is count = count+1; incremented. Since two instances of This statement is executed twice since two SalesPerson object were created, two SalesPerson objects were instantiated. Finally, independent copies of count, each having the the code prints out the number of value 1, were present. Figure 8-1 shows the SalesPerson objects instantiated via the state of the two created SalesPerson objects. statement Shared Attributes-Another solution can be System.out.println(count + " salespersons found in Listing 8-3 whereby count is declared have been created"); as static. Declaring count as static allows the The output: variable count to be shared among all instances of the SalesPerson class. Thus, "2 salespersons have been created” s1.count refers to the same memory location as s2.count. The statement: suggests that two SalesPerson objects were count = count+1; in the constructor created, and this is clearly correct. While the method therefore increments the same solution is correct, it is cumbersome since for shared copy of count as shown in Figure 8-2. each new instantiation of SalesPerson object, The output from the code: a fresh ”2 salespersons have been created” count = count+1; is correct statement has to be added into main(). An alternate class organisation is given in Listing 8-2, where count is incremented within the constructor method of the SalesPerson class. This strategy supports abstraction and is advantageous because the user does not have to bother with operations on count. First, while modules should be as independent as possible with minimal coupling, no module can be totally isolated from other code since it is unusual for a module to work in isolation. Thus, there must be entities on an object that are accessible externally. On the other hand, objects should reveal as little as possible of their internal workings so that there will be minimal dependence on such details. Ideally, objects will reveal information on a need-to- know basis. We have earlier seen the use of the visibility specifiers private and public
Private variables-are either used within the
class definition, or a public accessor method is implemented to provide the access required outside the class definition. We assume the Class Attributes-The static variable count is latter to be the case and provided a publicly also known as a class attribute. While a class accessible getCount() to return the value of definition specifies the structure and behavior count. of objects within, it may have its own Between the public and private extremes, attribute and method definitions. An attribute Java also allows for two more categories: definition that is preceded with the keyword protected and the default visibility of static is a class attribute. While we previously “friendly.” viewed the static variable count as shared amongst all instances, its association with the class is consistent. As a class attribute, it is also accessible to instances of the class. While the public and private specifiers allow Class Methods-In another change in Listing 8- for all-or-nothing access outside of the class 4, we make getCount() a class method by definition, the protected keyword makes prefixing it with the static keyword. The entities that follow it accessible to code results from the code is the same as that of fragments with its immediate subclass. For Listing 8-3 with just static count. Note the entities with no access specifier, friendly access is assumed. Here, access is given to difference in representation between the code fragments within the same package. getCount() method of Figure8-3 for Listing 8-4 Table 8-1 summarizes accessibility rules from and Figure 8-2 for Listing 8-3. In Figure 8-3, most restrictive to least restrictive. both SalesPerson objects s1 and s2 do not own the getCount() method since the method belongs to the SalesPerson class as represented by the outermost bubble surrounding instances s1 and s2.
Controlling Visibility-We have mostly ignored
the issue of visibility of attributes and methods. Any discussion on modularity is not complete without discussing visibility issues. Creating and Using packages-Throughout most of this book, you have imported packages into your programs. As you learned in previous Chapters, a package is a named collection of classes; for example, the java.lang package contains fundamental classes and is imported automatically into every program you write. You also have created classes into which you explicitly imported optional packages such as java.util and javax.swing. When you create classes, you can place them in packages so that you or other programmers easily can import your related classes into new programs. Placing classes in packages for other programmers increases the classes’ reusability