20-IOO-Lec01-Inheritance-new format PDF

Title 20-IOO-Lec01-Inheritance-new format
Author Anand Tiwari
Course Intermediate Object-Oriented Programming
Institution La Trobe University
Pages 24
File Size 515.9 KB
File Type PDF
Total Downloads 365
Total Views 432

Summary

Intermediate Object-Oriented ProgrammingLecture 1 HandoutCovers Topics Covered in the Subject The Concept of Inheritance How to Define Classes Related by Inheritance How to Use Classes Related by Inheritance Reading Savitch, Absolute Java, 7. Topics Covered in the SubjectTopic Lectures References 1 ...


Description

Intermediate Object-Oriented Programming Lecture 1 Handout Covers • • • •

Topics Covered in the Subject The Concept of Inheritance How to Define Classes Related by Inheritance How to Use Classes Related by Inheritance

Reading • Savitch, Absolute Java, 7.1

Topics Covered in the Subject Topic

Lectures

References

1

Inheritance and polymorphism

Lectures 1 - 5

Chapters 7-8 of Absolute Java

2

Exception Handling

Lectures 6-8

Chapter 9

3

File Input and Output

Lectures 9-11 Lecture 12: Revision

Chapter 10

4 5

Recursion Interfaces

Lectures 13-14 Lectures 15-16

Chapter 11 Chapter 13

6

Dynamic Data Structures

Lectures 17-18

Chapter 15

7

Generic Classes and Generic Methods

Lectures 19-21

Chapter 14

8

Abstract Data Types, Design Patterns

Lectures 22-23 Lecture 24: Revision

Chapter 12

9

Testing techniques

To be covered in lab exercises and assignment

Assumed Background This is the second course in programming in Java; the first course being CSE1OOF. You should be comfortable with the following • • • • • • •

Primitive data types The String class The Scanner class (to read data entered via the keyboard) Conditional statements Loops Classes and Objects Arrays (including arrays of objects)

Review Exercise As a quick check about your background for this subject, try the review exercise below. Develop a program to manage a list of employees (up to 100 employees). Each employee has an ID (a unique string), a name and a salary. The program will manage a list of employees and will allow us to: i. add new employees, ii. change the salary of a employee (given the ID), iii. delete employee, iv. sort the employees by ID , v. sort the employees by name, and vi. returns a string that can be used to display the employee list. You are to write three classes: a. class Employee, representing an employee (and a class to test this class) b. class EmployeeList, which maintains the collection of employees and provides methods to manage the collection c. class EmployeeListTester, to test the EmployeeList class

1

Inheritance: Definition and Its Fundamental Role

1.1

Definition

The concept of inheritance can be defined as follows: Inheritance is the mechanism that allows a class, called the derived class, to inherit attributes and methods of another class, called the base class. • The base class is also known as the parent class or superclass. • The derived class is also known as the child class or subclass. • We also say that the derived class extends the base class. • Note that the term “superclass” is a little ambiguous. It can mean the “immediate superclass” (the parent class) or “an indirect superclass”. Similarly for the term “subclass”. However, in most cases, there is no danger caused by this ambiguity: the context will make the intended meaning clear.

1.2

Importance

Inheritance is a feature that plays a fundamental importance in object-oriented in general and in Java programming in particular. So why is it such an important feature? To gain an insight into this issue, let us consider a typical scenario where inheritance can be used with great advantages. Suppose we have an application which we keep information about employees of an organization. Suppose employees are of two types: full-time employees and part-time employees. Also, • Certain information is kept for both types of employees, e.g. id, name, address, phone numbers. (Common attributes) • Certain operations are common to both, e.g. retrieve contact details. (Common methods) • But there is, as expected, information that is relevant to full-time employee but not for part-time employee, e.g. salary, and vice versa, e.g. hourly payment rate. (Different attributes) • In addition, some operations may be carried out differently, e.g. the way we calculate weekly payments. (Different behaviors) Now, let us ask: what would happen if we do not have this feature of inheritance? Quite clearly, without the inheritance mechanism, • We would have to define two separate classes: one for full-time employee and one for part-time employee. In doing so, we would have to repeat all of the definitions of the common features. • Moreover, there is a bigger price to pay: the fact that the two classes have certain shared features is completely lost. The shared features are not explicitly represented. Therefore, we simply cannot exploit what they have in common. We have to treat them as two separate classes, with nothing in common between them. Indeed, to

In contrast, with inheritance mechanism, • We can first define the common features in class Employee. • Then we define classes FullTimeEmployee and PartTimeEmployee by extending class Employee. By extending class Employee, we automatically inherit all its features. We only need to define the extra features specific to each of the derived classes. • Once we have represented the shared features and the differences explicitly, we are in a position to exploit these representations. More specifically, when we use these classes in our application, depending on whichever case is appropriate, – We can treat FullTimeEmployee and PartTimeEmployee instances in the same way (according to what are defined in Employee) – Or we can treat them differently (according to what are defined in FullTimeEmployee and PartTimeEmployee), That is, to share when it is appropriate to share and to differentiate when it is appropriate to differentiate. This is very much the story of “polymorphism”, which we will cover later in this lecture.

To sum up, in practice, we often deal with objects with the following characteristics: • The objects share some features (attributes and/or methods) in common • But there are also some variations among them In such cases, inheritance, together with polymorphism, provides a very natural and effective mechanism • To exploit the common features, and at the same time • To allow for the differences

1.3

Procedure

In using inheritance, we often use the following basic procedure: 1. Design the inheritance class hierarchy 2. Implement the superclasses and subclasses 3. Use the classes. At this stage, polymorphism will play an important role

In the following sections, we illustrate this basic procedure with an example.

2 2.1

Designing inheritance hierarchies Class Hierarchy Design Process

We can use the design process given below. This process, which is based on common sense, is straight forward, and sufficient for our purpose:

1. Identify the classes and their relationships. 2. Identify the attributes for the classes. 3. Identify the methods for each of the classes. In particular, for each derived class, determine which methods in the base class it should override (re-define).

2.2

Example

Consider the situation in which we maintain information about students and staff of a university. Suppose the following is the information we are interested in: • Each student and staff has an ID and a name • For each student, we also record the course he or she enrolls in • For each staff, we record the name of the department he or she belongs to Identify classes and their relationships We observe that • Students and staff have something in common (e.g. id and name) • But they also have something different (e.g. course for student, and department for staff) Exploiting the common features of students and staff, we would model the situation with three classes • Class Person to capture common attributes and behaviors • Classes Student and Staff to represent student and staff Regarding their relationships, class Person is the base class of classes Student and Staff. In other words, Student and Staff are derived classes of Person, and as such, they inherits attributes and methods of class Person. Identify the classes’ attributes It is clear that • Class Person should have the two attributes that are common to both students and staff: id and name • Class Student should have an additional attribute to store the name of course the student is enrolled in • Class Staff should have an additional attribute to store the name of the department the employee belongs to

Identify the classes’ methods Class Person would have constructor (to initialize id and name), get methods to get the id and name, and a toString method (to display id and name). Class Student would have constructor (to create Student instance), a get method to get the name of the course, and a toString method (to display id, name and course). Similarly, class Staff would have constructor (to create Staff instance), a get method to get the name of the course, and a toString method (to display id, name and department). The classes and their relationships are shown in the diagram below, using the Unified Modeling Language (UML) notation. The inheritance relationship is represented by an arrow, with a triangle arrow head, from the subclass to the superclass.

The above diagram contains a lot of information: • Person is the base class • Student is a derived class • Student inherits all attributes and methods of Person. That is, – Student automatically has attributes id and name – Student automatically has methods getId() and getName() • Student has an additional attribute of its own: course • Student has an additional method of its own: getCourse() • Student overrides (re-defines) the method toString(), which it inherits from the super class Person We say that class Student overrides method toString in class Person because: – Method toString is defined in the superclass Person – The same method, with the same signature, is defined in the subclass Student • Similar details can also be observed for the Staff class

2.3

A closer look at the concept of inheritance – The IS-A relationship

We only use inheritance when the relationship between classes is an IS-A relationship For X to relate to Y by the IS-A relationship, we must be able to say that • X is a Y, or • X is a type of Y For example, • A motorcycle is a vehicle • A motorcycle is a type of vehicle • A carrot is a vegetable • A carrot is a type of vegetable

Exercise Are these pairs of classes related through inheritance? And if so, which is the base class and which is the derived class? 1. Bee and Insect 2. Car and Engine 3. Concert and Event 4. Product and Book What about? 5. Spiderman and Superhero

3

Implementing the classes in an inheritance hierarchy

3.1

Implementing the base class

It is straight forward to define (implement) a superclass such as Person: We just define it in the “usual” way. public class Person { private String id; private String name; public Person(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } public String toString() { return "Person[id: " + id + ", name: " + name + "]"; } }

3.2

Implementing the derived classes

To define a derived class, we often follow the following steps:

1. Use the extends keyword to declare that the subclass extends the superclass 2. Declare all the additional attributes of the subclass 3. Define the constructors of the subclass 4. Define additional methods of the subclass 5. Define the methods that override the methods in the super class. To override a method in the super class, we define a new method with the same signature and the same return type (or a subclass of this return type)

The general syntax of a derive class is shown below: public class DerivedClass extends BaseClass { // Declarations of additional attributes // Definitions of constructors // Definitions of additional methods // Definition of overriding methods }

Following this procedure, we have the following definition for the Student class: 1 2 3

public class Student extends Person // extends keyword { private String course; // additional attribute

4

public Student(String id, String name, String course) // constructor { super(id, name); this.course = course; }

5 6 7 8 9 10

public String getCourse() { return course; }

11 12 13 14

// additional method

15

public String toString() // overriding method { String description = "Student[id: " + getId() + ", name: " + getName() + ", course: " + course + "]"; return description; }

16 17 18 19 20 21 22 23 24

}

Let us note a few important points: On line 1, we declare that Student extends Person. This means that Student is a derived class of class Person. Java allows only single inheritance. This means that a derived class can extend only one based class. On line 7, the statement super(id, name) calls the constructor in the superclass Person to initialize the attributes id and name. We will cover subclass constructor in detail in the next lecture. On line 19, we need to use the public method getId to access the private attribute id of the superclass. Similarly for line 20.

3.3

Some simple test programs to illustrate basic inheritance aspects

Let us continue the example with a few simple programs, which illustrate further the nature of the relationship between Person and Student.

Test program 1 public class Tester { public static void main(String [] args) { Student s = new Student("P01", "Smith", "Computer Science"); // display details of the student System.out.println(s); } }

Output: Student[id: P01, name : Smith, course: Computer Science]

This test program shows that the derived class Student • Inherits all attributes of the base class (id and name) • Has additional attributes (course) • Overrides method toString defined in the superclass (which only displays id and name) to give it a new behavior (can display course as well)

Test program 2 public class Tester { public static void main(String [] args) { Student s = new Student("P01", "Smith", "Computer Science"); // display the name of the student System.out.println(s.getName()); } }

Output: Smith

This test program shows that the derived class inherits the method getName from the base class.

Test program 3 public class Tester { public static void main(String [] args) { Student s = new Student("P01", "Smith", "Computer Science"); // display the course taken by the student System.out.println(s.getCourse()); } }

Output: Computer Science

This test program shows that that the derived class can have additional methods.

3.4

Exactly, what are inherited?

To be precise, a derived class 1. Inherits all of the attributes of the base class 2. Inherits all of the non-private methods of the base class Note: Are private methods of the base class inherited or not? If you compare several textbooks or if you search on the Internet, you will see that some people say “yes” and others say “no”. This issue is hotly debated (again as can be seen on the Internet). On this issue, the author of our textbook tries to sit on the fence (see chapter 7). The issue is actually quite subtle, but it is correct to say that private methods are not inherited (and it is incorrect to say otherwise). We will briefly revisit this issue in lecture 5.

Note: Inheritance and polymorphism is about instance attributes and instance methods. Static attributes and static methods, by nature, should not be involved. See Appendix B if interested.

*** Now we know how to define subclasses. But to use superclasses and subclasses properly, and to fully exploit what they have to offer, we must understand • The Polymorphic Reference Rule (covered in the next section) • The Polymorphic Behavior Rule (covered in section after the next) Note: There are two aspects to polymorphism. One is about the use of references (the static aspect) and one is about how reference may respond to a method call (the dynamic aspect). The term “polymorphism” have been used to refer to one or both of these aspects. This overloaded way of using the terms can, and do, cause unnecessary confusion. To avoid this, and to bring out the two aspects more clearly, we used the more specific terms “polymorphic reference” and “polymorphic behavior” whenever necessary.

4

Using Classes in Inheritance Hierarchies – Part 1 Polymorphic Reference

4.1

Polymorphic Reference Rule:

A reference of a class type must refer to an instance of the same class or an instance of a subclass. In other words, the following situation is valid

Example 1 The following statements are valid: Person p1 = new Person("P01", "Bob"); Person p2 = new Student("P02", "Alice", "CS");

p1 and p2 are references of type Person. Hence, according to the rule stated above, they can refer to an instance of class Person (as does p1) or an instance of a subclass of Person (as does p2). Example 2 The following statement is invalid: Student s = new Person("P03", "Eve");

// ILLEGAL

s is a reference of type Student. It must refer to an instance of class Student or an instance of a subclass of Student. Clearly, the instance created by the statement is neither a instance of class Student nor an instance of a subclass of Student. Hence, the rule is violated and the statement is invalid. It will be rejected by the Java compiler. A lesson that we can draw here is: a reference of a class type cannot refer to an instance of a superclass. Example 3 Is the second statement below valid? Student s = new Student("P03", "Clarke", "IT"); Person p = s;

Or more specifically, does it conform to the rule stated above? Yes, it does. Because as a result of the assignment statement, p will refer to an instance of Student or one of its subclass (if any), which is an instance of a subclass of Person (the type of reference p).

Example 4 Is the second statement below valid? Person p = new Person("P04", "Duke"); Student s = p;

No. Reference s cannot refer to an instance of class Person. Example 5 And even the following sequence of statements is still illegal: Person p = new Student("P05", "Frank", "IT"); Student s = p; // ILLEGAL

Why? Because as far as the compiler is concerned, p could refer to an instance of class Person because reference p is of type Person (even though it is not the case in this example). The lesson we can draw from the examples is that: we can assign a subclass reference to a superclass reference, but not the other way round.

4.2

Another way to look at the rule

In applying the polymorphic reference rule, it can also be useful to bear in mind the following rule (which is often known as the Substitution Rule): Whenever a program expects (or can legally use) a superclass instance, we can substitute it with a subclass instance. (but not the other way round)

5

Using Classes in Inheritance Hierarchies – Part 2 Polymorphic Behavior

The way a reference responds to a method call depends on which class the referenced object belongs to. More specifically, we have

Polymorphic Behavior Rule: When a method call is made, the most specialized method available to the referenced object will be executed.

Example 1 Person p = new Person("P01", "Smith"); System.out.println(p);

• The method call p.toString() is made • The reference is of type Person • The object is an instance of class Pers...


Similar Free PDFs