vernonmath.comvernonmath.com/wp/wp-content/uploads/2015/12/text0…  · web viewis very popular...

33
Chapter IX Inheritance Chapter IX Topics 9.1 Introduction 9.2 Is-A and Has-A Relationships 9.3 Superclass and Subclass 9.4 Private and Protected Access 9.5 Multi-Level Inheritance 9.6 The Fish Class Case Study 9.7 Summary Chapter IX Introduction to OOP, Inheritance 403

Upload: doanmien

Post on 28-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Chapter IX

Inheritance

Chapter IX Topics

9.1 Introduction

9.2 Is-A and Has-A Relationships

9.3 Superclass and Subclass

9.4 Private and Protected Access

9.5 Multi-Level Inheritance

9.6 The Fish Class Case Study

9.7 Summary

Chapter IX Introduction to OOP, Inheritance 403

9.1 Introduction

Chapter VIII introduced Object Oriented Programming terminology. You learned that OOP uses the computer science features of encapsulation, polymorphism and class interaction. The major contribution and motivation for developing programs with Object Oriented Design is reliability. The previous chapter focused on encapsulation. Encapsulation is the OOP feature whereby the data of an object and all the methods, which access the data, are placed in the same container. Understanding encapsulation is very important in learning OOP, but it is a first step. There are other steps to follow and learning class interaction is the next important step along the OOP journey. There are three types of Class Interation. These are Inheritance, Composition and Utility. The main focus of this chapter is Inheritance. Composition will look at briefly. As for Utility Classes, you have been working with those for a while. These are classes which are not used to create objects, but still contain several useful methods. The Math class and the Expo class are both perfect examples of this.

You have already seen and used inheritance in many previous program examples. In chapter IV you were introduced to using graphics in Java and creating applets for web pages. In each of your applet programs the class heading was followed with the words extends Applet. Little was mentioned about those words, but those two little words indicate that the current class will be using features that have already been declared in the Applet class.

A programming language is initially so complex that it is often necessary to use various language features that are not immediately explained. Explaining everything may be very thorough, but such an approach will be very intimidating and certainly overwhelming. Now you are ready to explore inheritance.

9.2 Is-A and Has-A Relationships

Object Oriented Programming is very popular for a good reason. There are so many features that make a program better designed, more reliable, easier to test and simpler to update than previous, non-OOP programs used to be. You have already seen a fair amount of encapsulation and learned the benefits of placing methods and data in the same module, along with constructors. Now let us see

404 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

what inheritance can do for us. Do not be alarmed if you do not instantly see the great benefits of all this OOP stuff. OOP is very powerful, but it takes time to reach a comfort level with this programming approach.

Imagine that you are very creative in designing custom camper vans. You know just how to replace regular seats with comfortable “captain” seats, add attractive paneling, install a small bathroom, provide lots of lights, install an entertainment system, and include many other goodies to make a simple van become a terrific camper vehicle for long road trips. Now, are you interested in putting together the basic chassis, the frame, the doors, the engine, the transmission, the drive shaft, the air-conditioning and all the other details that a van requires? No, not at all. Engines, transmissions and air-conditioning are not your concerns. Your only concern is designing a comfortable, custom camper van. The solution is to go out and get a fully functional basic van. Now with that basic van you can get to work. This means that any one of your custom vans first and foremost is-a-van. This is a very important concept and it is called the is-a relationship. Geometry does a nice job explaining this concept.

Geometry starts with very elementary concepts like points and lines. Then theorems and definitions are created that continually build upon previous theorems. Everywhere the assumption is that previous definitions may be used. For example, the definition of a rectangle does not need to start from scratch. You can state that a rectangle is a parallelogram with four right angles. The assumption is that the definition of a parallelogram is known. This process can continue by stating that a square is a rectangle with four equal sides. All through Geometry you will see the is-a statement used. This style of definition is very efficient. You establish a logical sequence of information and provide definitions that are based on a clear understanding of previous elements in the sequence. Basically, you stop reinventing the wheel on a regular basis.

Let us switch to computer science and see how this inheritance business might apply. You are a number-one-awesome programmer and you have just finished a considerable effort to create a Window class. Now this Window class is a beauty, because you can now display a window anywhere on the monitor. The window can minimize, maximize and you can drag the window to any location. You are rightfully very proud of your new Window class.

Now you want to expand the capability of your window and use it to enter text. This adds a whole new dimension of capabilities to your humble Window class. Now, your new class, let us call it TextWindow, needs to still do everything that the plain old vanilla Window class did, and more. It is possible to start from scratch, but that would be as efficient as our van converter person who first builds his own vans from scratch before customizing them for special needs. The secret is to start with the Window class and use all its capabilities for a new class called TextWindow. In computer science we say that TextWindow inherits from Window. Such an approach saves time and it adds tons of reliability. Just

Chapter IX Introduction to OOP, Inheritance 405

imagine that you are using an existing class that withstood the test of time. The class has been used over and over again, and all the bugs are corrected. Everybody is happy with your nifty Window class.

Now do not touch or alter Window. Start a new class, but do it in such a way that it is capable of using all the nicely tested features that are available with the existing Window class. In a nutshell that is inheritance.

Inheritance Definition

Inheritance is the process of using features (both attributesand methods) from an existing class. The existing classis called the superclass and the new class, which inheritsthe superclass features, is called the subclass.

Students frequently make a common mistake with inheritance. They confuse the is-a relationship with the has-a relationship. Both relationships are very useful in computer science, but only one is inheritance. Go back to the van example. Our van custom converter started with a fully functional van and customized it. The finished product is-a van.

Now when the van was assembled it was a different story. Many different assembly lines converged to create the van. The van has-an engine, and it has-a transmission, and it has doors. The van is built with many parts, but it is incorrect to state that a van is-a door. This different has-a relationship is called composition.

The confusion starts because in both cases something new is created with existing components. However there is a big difference between the two creations. With composition a new item is created that is composed of many existing parts. This is the case of assembling a van with a frame, wheels, doors, seats, engine, and all the other parts.

Now inheritance also uses something that already exists, but the whole item is used and then enhanced. A square is a special type of rectangle. A tiger is one particular type of cat. An off-road truck is first a truck. Take the example of the off-road truck. You can buy a regular truck. Now you put in special shocks that provide greater clearance and toughness. You also add four-wheel drive and a locking differential feature. You add special tires that will do well in mud and snow and your original truck is now an off-road truck. However, after all these changes it still is-a truck.

406 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

“Is-A” and “Has-A” Relationships

The creation of new classes with the help of existing classesmakes an important distinction between two approaches.

An "is-a" relationship declares a new class as a special“new-and-improved” case of an existing class. In Geometry,a parallelogram "is-a" quadrilateral with special properties.

A “has-a” relationship declares a new class composed ofan existing class or classes. A line “has” points, a square“has” lines, and a cube “has” squares.

A truck "is-a" car, but it "has-an" engine.

In computer science an "is-a" relationship is calledinheritance and a "has-a" relationship is called composition.

9.3 Superclass and Subclass

The previous section was strictly theoretical inheritance information. Hopefully you understand the concepts of inheritance and composition better. In this section you need to pull up a variety of Java program examples and see how inheritance is used in an actual program.

We will start simple – that is a shock – and demonstrate inheritance without constructors or any fancy methods. Program Java0901.java, in Figure 9.1 shows a program that starts with a Person class. The Person class is not very impressive since it has only one attribute, age, and only one method, showAge. A second class, Student, is equally skimpy and has one attribute, grade, and one method, showGrade. Something must be wrong, because Java does not like this program and provides an error message.

Chapter IX Introduction to OOP, Inheritance 407

Figure 9.1

// Java0901.java// This program presents a <Person> class and a <Student> class.// The main method calls the <showAge> method with a <Student> object.// This program will not compile.// Java cannot find the <showAge> method.

public class Java0901{

public static void main(String args[]){

System.out.println("\nJAVA0901\n");Student tom = new Student();tom.showAge();tom.showGrade();System.out.println();

}}

class Person{

private int age;

public void showAge(){

System.out.println("Person's Age is unknown right now");}

}

class Student{

private int grade;

public void showGrade(){

System.out.println("Student's Grade is unknown right now");}

}

408 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

This program creates a Student object, called tom. tom calls two methods, which are showAge and showGrade. Java has every right to be upset. Method showAge is a member of the Person class. You need a Person object to have access to method showAge.

The previous program was shown to remind you that it is not possible to access methods, including public methods, unless you have the proper object. Remember that Java syntax requires that you start with the toolkit name, which is tom (a Student object) in this case. After the toolkit name, you can proceed and access public tools, like showGrade.

All of this is true, but with inheritance it is possible to access a tool that is not in your own container. You inherit access to the tool. Program Java0902.java in Figure 9.2, shows the required syntax to implement inheritance. Person is the superclass, and Student is the subclass, which inherits from Person. The declaration of the Student class starts with the customary statement class Student, and then it is followed with extends Person. The keyword extends is the secret of inheritance in Java syntax. With extends the Java compiler is told that the new subclass has access to the features of the superclass, which is mentioned after the extends statement.

Do you see proof of inheritance? Take a look at the main method. Only one object is constructed. It is tom, which is a Student object. Now observe that the tom object calls both the showAge and showGrade methods. This is great but showAge is not a Student method. The previous program generated an error message with this very same approach. Now with inheritance it is possible to access this method precisely because Student is a subclass of superclass Person.

Figure 9.2

// Java0902.java// This program demonstrates fundamental inheritance with <extends>.// The <Student> is declared as a subclass of the <Person> superclass.// Now the program compiles and executes correctly.

public class Java0902{

public static void main(String args[]){

System.out.println("\nJAVA0902\n");Student tom = new Student();tom.showAge();tom.showGrade();System.out.println();

}}

Chapter IX Introduction to OOP, Inheritance 409

class Person{

private int age;

public void showAge(){

System.out.println("Person's Age is unknown right now");}

}

class Student extends Person{

private int grade;

public void showGrade(){

System.out.println("Student's Grade is unknown right now");}

}

Figure 9.2 Continued

JAVA0902

Person's Age is unknown right nowStudent's Grade is unknown right now

Program Java0903.java adds constructors to the Person and Student classes. Constructor methods are nothing new, but you do need to observe something very interesting that further proves that some type of inheritance action is brewing behind the scenes during program execution. Once again only a Student object is instantiated. You would expect that the creation of the tom object activates a call to the Student constructor, and it does. However, take a look at Figure 9.3 and you will see in the output of this program that the constructor of Person is called first. Are you surprised by this action or does it make sense that the constructor of the superclass is called first? Keep in mind that the program does not have any instance of the Person class anywhere in sight. tom is the only object visible in the main method.

Go back to the van analogy. If a custom van is-a van, does it not start with a plain-old-vanilla van first? In other words, is it not required first to construct a van before you can construct a custom van? This is precisely what happens in program Java0903.java. One object is instantiated, but the tom object starts its life by first becoming a Person and then continuing to become a Student.

410 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

Figure 9.3

// Java0903.java// This program adds constructors to the <Person> and <Student> classes.// Note how the <Person> constructor is called, even though there does// not appear to be a <Person> object instantiated.

public class Java0903{

public static void main(String args[]){

System.out.println("\nJAVA0903\n");Student tom = new Student();System.out.println();

}}

class Person{

private int age;

public Person(){

System.out.println("Person Constructor");age = 17;

}}

class Student extends Person{

private int grade;

public Student(){

System.out.println("Student Constructor");grade = 12;

}}

JAVA0903

Person ConstructorStudent Constructor

Inheritance and Constructors

When an object of a subclass is instantiated, the constructor of the superclass is called first, followed by a call to the constructor of the subclass.

Chapter IX Introduction to OOP, Inheritance 411

9.4 Private and Protected Access

There has been considerable evidence provided by previous program examples that a class, which extends another class results in a superclass and subclass relationship. This relationship allows a subclass to access members of the superclass. The truth is that this access has only been tested by the access of superclass methods. Does this access also apply to the data attributes of a superclass? Check out program Java0904.java, in Figure 9.4, to get the answer to that question. You will see that private data age, from the Person class is accessed by the showData method of the Student class. How will the compiler react to this type of programming?

Figure 9.4

// Java0904.java// This program shows that the subclass does not have access to the private data// of the superclass. This program will not compile.

public class Java0904{

public static void main(String args[]){

System.out.println("\nJAVA0904\n");Student tom = new Student();tom.showData();System.out.println();

}}

class Person{

private int age;

public Person(){

System.out.println("Person Constructor");age = 17;

}}

class Student extends Person{

private int grade;

public Student(){

System.out.println("Student Constructor");grade = 12;

}

412 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

public void showData(){

System.out.println("Student's Grade is " + grade);System.out.println("Student's Age is " + age);

}}

Figure 9.4 Continued

The compiler is not pleased. An attempt is made to access private data and you had better keep your fingers off. Local methods only please. Everybody else is not invited or allowed access. Now we have made a big deal in past chapters that data should only be accessed by special methods that access the data correctly. Basically, this may mean that you are not very disturbed about an inability to access data by a subclass. On the other hand, you could argue that a subclass is supposed to inherit all the features of the superclass, and does that not include the data of the superclass? This is a good point and Java inheritance allows you to have your cake and eat it too. It is possible to access data of the superclass, but that is not possible if the superclass data is declared private. The declaration needs to change to protected. Program Java0905.java, in Figure 9.5, looks like the previous program, except the super class data is declared protected. This time the program compiles and the subclass has access to the data of the superclass.

Figure 9.5

// Java0905.java// This program changes private super class data access to "protected".// The Student class can now access data from the Person class.

public class Java0905{

public static void main(String args[]){

System.out.println("\nJAVA0905\n");Student tom = new Student();

Chapter IX Introduction to OOP, Inheritance 413

tom.showData();System.out.println();

}}

class Person{

protected int age;

public Person(){

System.out.println("Person Constructor");age = 17;

}}

class Student extends Person{

private int grade;

public Student(){

System.out.println("Student Constructor");grade = 12;

}

public void showData(){

System.out.println("Student's Grade is " + grade);System.out.println("Student's Age is " + age);

}}

Figure 9.5 Continued

JAVA0905

Person ConstructorStudent ConstructorStudent's Grade is 12Student's Age is 17

Life used to be simple. public items in a class can be accessed outside the class and private items can only be accessed inside the class. Now protected adds confusion to the simple rules. What does protected mean? Protected is an interesting hybrid. With protected you can have access from outside the class, but only if you are a subclass. Any other class has no access.

414 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

Public, Private & Protected

Attributes & methods declared public can be accessed by methods declared both outside and inside the class.

Attributes & methods declared private can only be accessed by methods declared inside the class.

Attributes & methods declared protected can be accessed by methods declared inside the class or subclass.

9.5 Multi-Level Inheritance

How far does inheritance go? Does it resemble life? A parent has a child and this child grows up to become a parent. Now there is a person who is a parent and a child at the same time. Can a Java program have a class, which is a subclass of a superclass and then simultaneously become the superclass of another subclass? It certainly can and program Java0906.java, in Figure 9.6, demonstrates three classes with such relationships.

Figure 9.6

// Java0906.java// This program demonstrates inheritance at three levels.

public class Java0906{

public static void main(String args[]){

System.out.println("\nJAVA0906\n");Cat cat = new Cat("Tiger");System.out.println();System.out.println("Animal type: " + cat.getType());System.out.println("Animal weight: " + cat.getWeight());System.out.println("Animal age: " + cat.getAge());System.out.println();

}}

Chapter IX Introduction to OOP, Inheritance 415

class Animal{

protected int age;

public Animal(){

System.out.println("Animal Constructor Called");age = 15;

}

public int getAge(){

return age;}

}

class Mammal extends Animal{

protected int weight;

public Mammal(){

System.out.println("Mammal Constructor Called");weight = 500;

}

public int getWeight(){

return weight;}

}

class Cat extends Mammal{

protected String type;

public Cat(String t){

System.out.println("Cat Constructor Called");type = t;

}

public String getType(){

return type;}

}

416 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

Figure 9.6 Continued

JAVA0906

Animal Constructor CalledMammal Constructor CalledCat Constructor Called

Animal type: TigerAnimal weight: 500Animal age: 15

When you talk about Multi-Level Inheritance, be careful that you say it properly. There is something else called Multiple Inheritance which sounds similar, but that is completely different. In Multiple Inheritance, one subclass can have multiple super classes. The best way to explain the difference is to look at the example in Figure 9.7. A dinosaur is-a reptile, and a dinosaur is-an extinct animal. Something else to keep in mind, Java allows Multi-Level Inheritance, but it does NOT allow Multiple Inheritance.

Some students who may be present in this introductory computer science course have already investigated programming on their own. Perhaps you have taught yourself or maybe you have parents who are computer science professionals. In such a case you may have knowledge of the programming language C++. Multiple Inheritance is possible in C++, but not in Java.

Figure 9.7

Chapter IX Introduction to OOP, Inheritance 417

9.6 The Fish Class Case Study

This chapter will finish with a graphical demonstration of inheritance. This demonstration will be in the form of a case study, which starts with a simple fish displayed at a fixed location, programmed in the constructor. In four stages the fish becomes bolder and performs more actions.

Do keep in mind that the actual Fish class is not altered. Program Java0907.java starts with the Fish1 class. Figure 9.8 shows that the fish appears and parks itself. Later stages will extend the original class and add more features by creating subclasses. Inheritance makes changes in two fundamental ways. First, an existing method in a superclass is re-defined in a subclass. Second, a subclass creates a new method that does not exist in the superclass.

The Fish1 class has three attributes. A set of (x,y) coordinates and a direction to determine which way the fish is facing. A Fish1 object can only face North, East, South and West. Initial attribute values are specified in the Fish1 constructor.

Figure 9.8

// Java0907.java// The Fish class, Stage #1// The <Fish1> class can only draw a fish at a fixed starting location.

import java.awt.*;import java.applet.*;

public class Java0907 extends Applet{

public void paint(Graphics g){

Fish1 f1 = new Fish1();f1.drawFish(g);

}}

class Fish1{

protected int x; // center X coordinate of the fishprotected int y; // center Y coordinate of the fishprotected int direction; // one of four directions fish is facing: 0-N, 90-E, 180-S, 270-W

public Fish1(){

x = 500;y = 300;direction = 0;

}

418 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

public void drawFish(Graphics g){

Expo.setColor(g,Expo.black);switch (direction){

case 0:Expo.fillOval(g,x,y,15,30);Expo.fillPolygon(g,x,y+30,x-15,y+40,x+15,y+40);break;

case 90:Expo.fillOval(g,x,y,30,15);Expo.fillPolygon(g,x-30,y,x-40,y-15,x-40,y+15);break;

case 180:Expo.fillOval(g,x,y,15,30);Expo.fillPolygon(g,x,y-30,x-15,y-40,x+15,y-40);break;

case 270:Expo.fillOval(g,x,y,30,15);Expo.fillPolygon(g,x+30,y,x+40,y-15,x+40,y+15);break;

default:System.out.println("ERROR!!! Direction must be 0,90,180,270");

}}

}

Figure 9.8 Continued

Our fish is quite boring. Stage #2 adds some features. The Fish2 class adds an eraseFish method and a turnFish method. It is now possible to put a little animation in our fish. The turnFish method uses the Expo.delay method to slow down the fish erasure to 1 second. Without delay you will not observe any kind of animation. Our eyes are not that fast. This program can only be appreciated on the computer. Program Java0908.java, in Figure 9.9, does provide an execution, but it cannot demonstrate the fish turning. The actual program file includes the

Chapter IX Introduction to OOP, Inheritance 419

Fish1 class, which is not repeated in the textbook. It is considered good program design to place individual classes in their own file. We often tend not to follow that rule with program examples in this book for the sake of clarity. It is easier to comprehend a new concept when all the classes are placed in the same file.

Figure 9.9

// Java0908.java// The Fish class, Stage #2// The <Fish2> class inherits the <drawFish> method.// Additionally, it adds methods to erase the fish and to turn the fish.

import java.awt.*;import java.applet.*;

public class Java0908 extends Applet{

public void paint(Graphics g){

Fish2 f2 = new Fish2();f2.drawFish(g);f2.turnFish(g);f2.turnFish(g);f2.turnFish(g);f2.turnFish(g);

}}

class Fish2 extends Fish1{

public void eraseFish(Graphics g){

Expo.setColor(g,Expo.white);switch (direction){

case 0:Expo.fillOval(g,x,y,15,30);Expo.fillPolygon(g,x,y+30,x-15,y+40,x+15,y+40);break;

case 90:Expo.fillOval(g,x,y,30,15);Expo.fillPolygon(g,x-30,y,x-40,y-15,x-40,y+15);break;

case 180:Expo.fillOval(g,x,y,15,30);Expo.fillPolygon(g,x,y-30,x-15,y-40,x+15,y-40);break;

case 270:Expo.fillOval(g,x,y,30,15);Expo.fillPolygon(g,x+30,y,x+40,y-15,x+40,y+15);break;

420 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

default:System.out.println("ERROR!!! Direction must be 0,90,180,270");

}}

public void turnFish(Graphics g){

Expo.delay(1000);eraseFish(g);direction += 90;if (direction == 360)

direction = 0;drawFish(g);

}

}

Figure 9.9 Continued

Slowly the fish gets better. Our fish can turn, but wants to check out some new scenery. This is accomplished in Java0909.java, in Figure 9.10. Stage #3 adds the Fish3 class, which creates one new small method, called moveFish. It is now possible to move the fish to a specified coordinate. It probably appears that some of this stuff resembles what you have seen in the GridWorld case study. The grid is not visible, but the fish seems to move to some new location on an invisible grid. Actually, the invisible grid is the graphics display itself, which is divided into pixels. This program would look better if it used the grid appearance of the GridWorld case study, but that will add more code and possible confusion. The aim of our little case study here is to demonstrate inheritance. So far we have shown you several levels of inheritance, and in each stage new methods were added for additional fish features.

Chapter IX Introduction to OOP, Inheritance 421

Figure 9.10

// Java0909.java// The Fish class, Stage #3// The Fish3 class adds method <moveFish>, which moves the <Fish>// object to a specified coordinate.

import java.awt.*;import java.applet.*;

public class Java0909 extends Applet{

public void paint(Graphics g){

Fish3 f3 = new Fish3();f3.drawFish(g);f3.moveFish(g,800,200);f3.turnFish(g);f3.moveFish(g,300,500);f3.turnFish(g);

}}

class Fish3 extends Fish2{

public void moveFish(Graphics g, int newX, int newY){

Expo.delay(1000);eraseFish(g);x = newX;y = newY;drawFish(g);

}}

422 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

Figure 9.10 Continued

Inheritance is not limited to a subclass creating new methods. It is very common to take some existing superclass method and alter or re-define such a method in the subclass. For example, a MonsterTruck is-a Car, but you do not really want to put generic Car tires on a MonsterTruck, even though you would inherit them. Instead, you install huge, massive tires. You effective define a MonsterTruck by re-defining their tires.

Stage #4 demonstrates re-defining with program Java0910.java, in Figure 9.11. Method moveFish is re-defined in the Fish4 class. The change is extremely minor. The call to eraseFish, used in the original moveFish definition, is removed. The result is that the fish leaves a trail of its previous positions. Once again there are definite shades of the GridWorld case study where a bug leaves flowers behind. The program code of our fish classes does not resemble any GridWorld code, but the idea certainly has been motivated by the excellent program written by Cay Horstman.

Stage #4 also adds a new constructor. It is now possible to specify the starting position of the Fish4 object. The main method uses a loop structure to call method moveFish repeatedly and you will see that a horizontal display of fishes is drawn by the latest stage.

Chapter IX Introduction to OOP, Inheritance 423

Figure 9.11

// Java0910.java// The Fish class, Stage #4// The <Fish4> class re-defines the <moveFish> method.// <Fish> objects will now move without erasing themselves.// Additionally, the <Fish4> class adds a constructor, which// draws a <Fish> object at a specified starting location// and facing in a specified direction.

import java.awt.*;import java.applet.*;

public class Java0910 extends Applet{

public void paint(Graphics g){

int xPos = 100;int yPos = 100;int direction = 90;Fish4 f4 = new Fish4(xPos,yPos,direction);for (int k = 1; k <= 8; k++){

xPos += 80;f4.moveFish(g,xPos,yPos);

}}

}

class Fish4 extends Fish3{

public Fish4(Graphics g, int xPos, int yPos, int dir){

x = xPos;y = yPos;direction = dir;drawFish(g);

}

public void moveFish(Graphics g, int newX, int newY){

Expo.delay(1000);x = newX;y = newY;drawFish(g);

}}

424 Exposure Java 2015, Pre-AP®CS Edition 05-21-15

9.7 Summary

This chapter provided a little information into a variety of topics that are all closely related. Java is an object oriented programming language, and the three corner stones of OOP are encapsulation, inheritance and polymorphism. Chapter VIII started with a close look at encapsulation. This chapter continued by focusing on inheritance.

With inheritance it is possible to use existing classes with all their available features, both methods and attributes. The existing class is called the superclass and the new class derived from the superclass is called the subclass. Inheritance involves an "is-a" relationship. This means that first and foremost every subclass "is-a" superclass. Geometry provides good examples, such as a square is-a rectangle. In Java the reserved word extends is used to indicate that a class declaration is a subclass of an existing superclass.

It is very important not to confuse inheritance with composition. A new class can be declared that includes existing components. A new class may have multiple members, which are existing classes. In such a case the new class demonstrates a "has-a" relationship because it has certain other members. We can also say that the new class is composed of other components and hence the term composition. In Geometry we do not say a rectangle is-a lines, but we can say a rectangle has lines.

This chapter also introduced the protected reserved word, which is frequently used with inheritance. Superclass attributes that are private cannot be accessed by a subclass. However, if a superclass attribute is declared protected it can be accessed by subclass methods, while simultaneously denying access by any other program areas outside the superclass and subclass.

The biggest benefit of inheritance is the ability to use program components that have already been created and tested. New and improved versions of existing components can be designed without starting from scratch. This improves program design efficiency as well as increase program reliability.

You will find that a subclass brings two types of changes to an existing class. First, the subclass can introduce one or more new methods to add new features. Second, the subclass can re-define an existing class. Examples of both types of changes were demonstrated with the Fish case study.

Chapter IX Introduction to OOP, Inheritance 425

426 Exposure Java 2015, Pre-AP®CS Edition 05-21-15