Block 1 Unit 3 Using Inheritance Khalid Ali

Block 1 Unit 3 Using Inheritance Khalid Ali 21/10/2006 M 301 - Khalid Ali

Information n Section 103 • An Extra Lecture will be held on 09/11/2006 at 12: 00 – 14: 00 just before our regular Lecture Time. In Room B 3. • The Quiz will be held on 23/11/2006. n Section 204 • An Extra Lecture will be held on 23/11/2006 at 12: 00 – 14: 00 in Room B 3. • The Quiz will be held on that date. . 21/10/2006 M 301 - Khalid Ali 2

Aims n n n Develop programs that will respond to mouse-related events. Use the Vector class for holding objects. Write simple exception handlers. Develop programs using inheritance. Understanding the Polymorphism. 21/10/2006 M 301 - Khalid Ali 3

The Pin. Ball. Game game n n Users fire a ball from a small square. Balls encounters a variety of targets and fall back to the ground. User scores points when balls hit targets. The scores depends on the type of targets hit by the balls. 21/10/2006 M 301 - Khalid Ali 4

The Class Pin. Ball. Fire n Is a fire button for the application n It knows how to draw itself. n It can test a point to see if it is in the region of the fire button and returns a ball. 21/10/2006 M 301 - Khalid Ali 5

The Pin. Ball Class n n Pinball extends the class Cannon. Ball, even though there is no cannon in the pinball game. Fired from a Pin. Ball. Fire and responded to gravity just like cannon ball. 21/10/2006 M 301 - Khalid Ali 6

The Pin. Ball Class Method is inherited from the constructor in the parent class Cannon. Ball import java. awt. *; public class Pin. Ball extends Cannon. Ball { public Pin. Ball (Point loc) { super(loc, 8, -2 + Math. random(), -15); } } public Rectangle box() { int r = radius(); return new Rectangle(location(). x-r, location(). y-r, 2*r); } 21/10/2006 M 301 - Khalid Ali 7

The Cannon. Ball Class import java. awt. *; public class Cannon. Ball extends Ball { public Cannon. Ball (Point loc, int r, double dx, double dy) { //invoke Ball's constructor super(loc, r); This Code gets executed from the set. Motion(dx, dy); previous call } public double Gravity. Effect = 0. 3; } public void move () { change. In. Y += Gravity. Effect; //short for change. In. Y=change. In. Y+Gravity. Effect; super. move(); //update the ball position } 21/10/2006 M 301 - Khalid Ali 8

The Cannon. Ball Class n super(loc, r); • invokes the constructor of its parent class Ball. n set. Motion(dx, dy); • will set the direction of the initial move of the ball. 21/10/2006 M 301 - Khalid Ali 9

The Vector Class n n n Need a structure that holds an undetermined number of balls. Unlike arrays, Vector can dynamically grow as elements are inserted. It could only hold objects or wrapped primitive data type. 21/10/2006 M 301 - Khalid Ali 10

Accessing elements of Vector n balls = new Vector(); n balls. add. Element (new. Ball); For (int i = 0; i < balls. size(); i++) Pin. Ball a. Ball = (Pin. Ball)balls. element. At(i); 21/10/2006 M 301 - Khalid Ali 11

Mouse Listeners n The concept is that objects wait and listen. n In our example, to create a listener, we define a class that implements the following interface. n public interface Mouse. Listener { public void mouse. Pressed(Mouse. Event e); public void mouse. Released(Mouse. Event e); public void mouse. Entered(Mouse. Event e); public void mouse. Exited(Mouse. Event e); } 21/10/2006 M 301 - Khalid Ali 12

Mouse Listeners n Instead of implementing all methods. n Java provides a class named Mouse. Adapter. n n The class Mouse. Adapter implements Mouse. Listener with empty methods. Programmer can inherit from Mouse. Adapter and implements the needed methods. 21/10/2006 M 301 - Khalid Ali 13

Mouse Listeners n n That is what we do in our example. We define an inner class that defines Mouse. Listener by extending Mouse. Adapter. Private class Mouse. Keeper extends Mouse. Adapter { n An instance of this class is created and passed as argument to the method add. Mouse. Listener (new Mouse. Keeper()); 21/10/2006 M 301 - Khalid Ali 14

Running the Application n The run method repeatedly calls move. Balls to move the balls, repaints the window and sleep shortly for window to be redrawn. public void run() { while (true) { move. Balls(); repaint(); try { Thread. sleep(10); } catch(Interrupted. Exception e) {System. exit(0); } } } 21/10/2006 M 301 - Khalid Ali 15

Running the Application n The move. Balls routine cycles over the list of balls, moving each one. private void move. Balls() { for (int i = 0; i < balls. size(); i++) { Pin. Ball the. Ball = (Pin. Ball) balls. element. At(i); if (the. Ball. location(). y < Frame. Height) { the. Ball. move(); for (int j = 0; j < targets. size(); j++) { Pin. Ball. Target target = (Pin. Ball. Target) targets. element. At(j); if (target. intersects(the. Ball)) target. hit. By(the. Ball); } } 21/10/2006 M 301 - Khalid Ali 16

Adding targets n n n As in real pinball game, we need to add targets for the ball to encounter. Some targets add scores, some move balls and some swallow the balls. We need a Pin. Ball. Target interface. 21/10/2006 M 301 - Khalid Ali 17

The Pin. Ball. Target interface import java. awt. *; public interface Pin. Ball. Target { public boolean intersects(Pin. Ball a. Ball); public void move. To(int x, int y); public void paint(Graphics g); public void hit. By(Pin. Ball a. Ball); } n The above defines a common behavior for Peg and Wall. 21/10/2006 M 301 - Khalid Ali 18

The Spring Class n A Spring mimics the behaviour of a typical reallife pinball target which, when hit, gives the ball a slight ‘push’, that is, a small increase in velocity. 21/10/2006 M 301 - Khalid Ali 19

The Spring Class n The Spring class implements Pin. Ball. Target. n It implements all methods. n Describe all methods in the class. 21/10/2006 M 301 - Khalid Ali 20

Polymorphism / Polymorphic Variable for (int j = 0; j < targets. size(); j++) { Pin. Ball. Target target = (Pin. Ball. Target) targets. element. At(j); //Line 1 if (target. intersects(the. Ball)) target. hit. By(the. Ball); //Line 2 } n n The variable target is used to hold objects of type Pin. Ball. Target. Line 1, extracts an individual target from the vector targets and calls it target which is of type Pin. Ball. Target but actually holds targets of type Hole, Score. Pad, Peg and so on. 21/10/2006 M 301 - Khalid Ali 21

Polymorphism / Polymorphic Variable for (int j = 0; j < targets. size(); j++) { Pin. Ball. Target target = (Pin. Ball. Target) targets. element. At(j); //Line 1 if (target. intersects(the. Ball)) target. hit. By(the. Ball); //Line 2 } n n Thus, since target can refer to objects of different types (though they must all be subtypes of Pin. Ball. Target ), target is said to be a polymorphic variable. In line 2, the fact that target is a polymorphic variable means that the methods intersects and hit. By actually used, are those that apply to whatever type of object target currently refers to. 21/10/2006 M 301 - Khalid Ali 22

An Aspect of Polymorphism. n n n Spring and Wall both implements Pin. Ball. Target. A variable declared as Pin. Ball. Target could be holding either a Spring or a Wall. This is one aspect of polymorphism. 21/10/2006 M 301 - Khalid Ali 23

The Hole Class public class Hole extends Ball implements Pin. Ball. Target { ……. n n Inheritance is used when we have structural relationship Interface is used when we have behavioral relationship. 21/10/2006 M 301 - Khalid Ali 24

Inheritance and Interfaces n The difference between implementing an interface and extending a class is subtle. n Consider the definition of Hole: n The fact that Hole extends Ball means that, except where overridden, any method of Ball is available to objects of class Hole. n However, the fact that Hole implements Pin. Ball. Target means that Hole needs to implement the methods hit. By and intersects that are part of the Pin. Ball. Target interface. If it does not, the class Hole would not compile. (move. To and paint are already inherited from Ball) 21/10/2006 M 301 - Khalid Ali 25

The try statement n n Any code that can generate an exception should be placed in a try block. A try block can be followed by zero, one or more catch clauses. Each catch clause specifies the type of exception it can catch and an exception handler. 21/10/2006 M 301 - Khalid Ali 26

The try statement n The optional finally block is executed when an exception that is not explicitly handled by one of the given catch clauses occurs. 21/10/2006 M 301 - Khalid Ali 27

The variable world is static n The implementation of the method hit. By in Score. Pad consists of the single message: public void hit. By(Pin. Ball a. Ball) { Pin. Ball. Game. world. add. Score(value); } n The method add. Score is a member of the class Pin. Ball. Game 21/10/2006 M 301 - Khalid Ali 28

The variable world is static n n Since world is a public static variable defined in the class Pin. Ball. Game, it can be referred to in other classes by the construction: Pin. Ballgame. world Any static variable (declared public) can be referred to in other classes by prefixing it with its class name. You have met a similar construction in System. out. println (where out is a static variable of the class System). 21/10/2006 M 301 - Khalid Ali 29

Members of Score. Pad class n n The fact that the Score. Pad class has members named intersects and move. To is not immediately obvious from its class definition. These members are inherited from Hole and Ball respectively. 21/10/2006 M 301 - Khalid Ali 30

Understanding Inheritance n n Inheritance, we mean the property that instances of a child class can access both data and behavior associated with the parent class. Unless specified otherwise, all classes are derived from a single root class, named Object. 21/10/2006 M 301 - Khalid Ali 31

Understanding Inheritance n All methods of Ball are available to objects of Cannon. Ball. 21/10/2006 M 301 - Khalid Ali 32

Understanding Inheritance n Consider Pin. Ball class: A new method, box , is defined to help detect whether a ball has encountered a target. n If box was sent to object of Cannon. Ball, an error will be reported. 21/10/2006 M 301 - Khalid Ali 33

Subtype, Subclass and Substitutability. n A type of B is considered to be a subtype of A if: • An instance of B can be assigned to a variable declared as type A • That value can be used by the variable with no observable change in behavior. 21/10/2006 M 301 - Khalid Ali 34

Subtype, Subclass and Substitutability. n n A subclass refers to constructing a new class using inheritance (extends). In a majority of situations (not all), a subclass is also a subtype. 21/10/2006 M 301 - Khalid Ali 35

Subtype, Subclass and Substitutability. n The idea is that the type given in a declaration of a variable does not have to match the type associated with the value the variable is holding. Pin. Ball. Target target = (Pin. Ball. Target) targets. element. At(j); Target holds a variety of different types of values. (Hole, Peg, Wall, …). 21/10/2006 M 301 - Khalid Ali 36

Forms of Inheritance. n Specialization • The child class is a subtype of the parent class. (extends) n Specification • The parent defines behavior that is implemented in the child class. (implements) n Construction • Child class makes use of the behavior of the parent class but is not a subtype of the parent class. (extends and implements. To inherit the methods from the interface that we do not want to implement) 21/10/2006 M 301 - Khalid Ali 37

Forms of Inheritance. n Extension • Child class adds new functionality to the parent class, but does not change any inherited behavior n Limitation • The child class restricts the use of some of the behavior inherited from the parent class. n Combination • Inheritance and interface. (extends and implements or implements more than one interface). 21/10/2006 M 301 - Khalid Ali 38

Modifiers and Inheritance. n n n A static field is shared by all instances of a class. A static method can be invoked even when no instance has been created. Static data fields and methods are inherited the same way as nonstatic items, except that static methods cannot be overridden. 21/10/2006 M 301 - Khalid Ali 39

Modifiers and Inheritance. n Both methods and classes can be declared to be abstract. n An abstract method must be overridden by a subclass. n final is the opposite of abstract. When applied to a class, means the class cannot be subclassified. n When applied to method, method cannot be overridden. 21/10/2006 M 301 - Khalid Ali 40

The benefit of Inheritance n n Software Reusability Increase Reliability • Code that execute frequently tends to have fewer bugs. n Code Sharing • Two classes inherit from a single class. n Consistency of Interface • Classes that inherit from the same class will in fact inherit the same behavior and therefore objects will have similar interfaces. 21/10/2006 M 301 - Khalid Ali 41

The benefit of Inheritance n Software Components • Enables programmers to construct software using components. n Rapid Prototyping • When software is constructed out of components, developers can concentrate on a new portion of the system. n Polymorphism and Frameworks • Permits programmer to generate high-level reusable components that can be tailored to fit different applications by changing the low-level parts. n Information Hiding • No need to understand the nature of the component that we reuse. 21/10/2006 M 301 - Khalid Ali 42

The cost of Inheritance n Execution Speed • Inherited methods are often slower than specialized code. n Program size • The use of software library imposes a size penalty. n Message-Passing Overhead • Message passing is by nature a more costly operation n Program Complexity 21/10/2006 M 301 - Khalid Ali 43
- Slides: 43