54

212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux
Page 2: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

4 Composition

At this point in the course we are letting Laszlo take over almost completely. The treatment in the book of all the topics yet to come is detailed. The role of the subject guide for now on is simply to guide you gently through the material.

Chapters Four and Five are about the two principal techniques for reusing classes to build object-oriented systems. In Chapter Five you will learn more about inheritance and in Chapter Four you will learn about composition. Composition is the process of making classes that are built up as a composite of other classes. One way of looking at the two techniques is that inheritance implements an is-a relation and composition implements a has-a relation.

4.1 Composition and Aggregation

There are two ways of implementing has-a relations: composition and aggregation. The difference between the two is that if we say that a class A is composed in part by a class B, we mean that the instance of B that is defined as a component of an instance of A is entirely controlled by it. We have already seen examples of this: in the bouncing ball example from Chapter 1, the canvas is a component of the ball; in the second bouncing ball example the ball is a component of the ApplicationFrame. If the ApplicationFrame were to die, it would take the ball with it. That particular ball has no life outside of the ApplicationFrame. On the other hand, the same class could be part of several aggregate classes. This chapter is much more about composition than aggregation.

Section 4.1 of Laszlo gives a more extensive explanation of composition, aggregation and the distinction between them. You should read that now and then return to the subject guide.

4.2 Random Values

In Section 4.2 of the course text, Laszlo, several classes that generate random values are developed. They will all fit together in a network of associations having Java’s Random class, which implements a random number generator, at the centre.

A random number generator (really a pseudo-random) is a function that returns a sequence of numbers with no discernable pattern. The key is that every number is supposed to be just as likely to turn up as any other. The sequence of numbers always begins by applying the function to a number, called the seed of the sequence. The same generator with the same seed will always produce the same sequence of numbers. To get different, independent, random number sequences you need to make sure you start from different seeds. Just using the clock at different times will ensure that. The book suggests some ways of ensuring that the seeds are different. Note that there is no reason to think that if you start the random number generator with seeds that are near each other you will get similar sequences.

All of the random value generators in this chapter are based on the Random class, which generates random integers in the range from –maxInt to maxInt. The Class has two non-

2

Page 3: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

constructor methods: setSeed, which is a setter that does what it sounds like it does, and nextInt, which returns the next random number in the sequence.

In the Section of Laszlo, the Random class is used as the first component in building up, first, several specialised random number generators, and then random colour and random rectangle classes. These last two are then brought together as parts of a class that can draw many randomly sized and randomly coloured rectangles on a screen.

You should now read section 4.2 of Laszlo and come back to the subject guide, where the final program of the section is discussed briefly.

The final program in the section draws several rectangles on the screen. The rectangles are of random size, position and colour. Here is the sourcecode:

1. import java.awt.*;2. import javax.swing.*;3. import java.awt.geom.*;4. import banana.*;

5. public class PaintManyRectangles extends ApplicationPanel {

6. public PaintManyRectangles() {a. setBackground(Color.black); }

The main method simply makes then screen, makes the content and shows it:

7. public static void main(String[] args) {a. parseArgs(args);b. ApplicationPanel panel = new PaintManyRectangles();c. ApplicationFrame frame = new ApplicationFrame("Many

Rectangles");d. frame.setPanel(panel);e. panel.makeContent();f. frame.show();g. }

8. protected static int nbrRectangles = 100;9. protected static int minLength = 100, maxLength = 200;

There is an argument parsing method that will turn the String inputs to ints and then use them as the needed variable values.

10. public static void parseArgs(String[] args) {a. if ((args.length == 2) || (args.length > 3)) {b. System.out.println("USAGE: java PaintManyRectangles [n

[minLen maxLen]]");c. System.exit(1);d. }e. if (args.length > 0)f. nbrRectangles = Integer.parseInt(args[0]);g. if (args.length > 2) {h. minLength = Integer.parseInt(args[1]);

3

Page 4: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

i. maxLength = Integer.parseInt(args[2]);j. }k. }

From a-c we see that we will exit unless the length of args is 0, 1 or 3. The first argument will be the number of rectangles. If there are two more arguments, they will be the minimum and maximum lengths.

11. protected RectangleGeometry[] rectangles;

12. public void makeContent() { // construct a random rectangle generator rndRect

a. Dimension d = getFrame().getContentSize();b. Range frameWidth = new Range(0, d.width);c. Range frameHeight = new Range(0, d.height);d. RandomRectangle rndRect = e. new RandomRectangle(frameWidth, frameHeight);f. // set rndRect's width and height propertiesg. Range minMaxLengths = new Range(minLength, maxLength);h. rndRect.setWidthRange(minMaxLengths);i. rndRect.setHeightRange(minMaxLengths);j. // generate and save random rectanglesk. rectangles = new RectangleGeometry[nbrRectangles];l. for (int i = 0; i < nbrRectangles; i++)

i. rectangles[i] = rndRect.nextRectangle();m. }

This makes random rectangles: k makes an array of rectangles; l and l.i is a looping construct that makes the right number of rectangles (using an object of the RandomRectangle class) and puts them into the array; most of the rest of the method is setting the parameters of the rectangles.

13. public void paintComponent(Graphics g) {a. super.paintComponent(g);b. Graphics2D g2 = (Graphics2D)g; c. RandomColor rndClr = new RandomColor();d. for (int i = 0; i < rectangles.length; i++) {

i. g2.setPaint(rndClr.nextColor());ii. RectangleGeometry r = rectangles[i];iii. g2.fill(r.shape());

}}

}

The paintComponent calls upon a random colour generator. Within the loop d – d iii, the array made above is traversed and each rectangle is drawn and filled with the colours as they come from the sequence generated by the random colour generator.

Task: Compile and run this program. You will find it in the Chapter 4 source code folder in your CD.

Exercise: Now define a RandomEllipse class, and make variant of the DrawManyRectangles program that randomly draws shapes that could be either rectangles or ellipses.

4

Page 5: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

Exercises form Laszlo. You should now do the following Laszlo exercises: 4.3, 4.4, 4.8, 4.11, 4.13, and 4.14

4.3 Vectors and polymorphism

The next section of Laszlo introduces vectors as a way of having many components of a composite class. The Vectors are then used in the definition of a composite class called Polyline. A polyline (meaning many lines) is simply a sequence of points and line segments between them. A vector is used to represent a series of points on the screen. The line segments connecting adjacent points are implicit in the description.

Vectors are ordered collections of objects. As such, they are quite similar to the arrays we have already been using. However, there are two main differences between vectors and arrays:

a. The size of a vector is not fixed, but changing dynamically, so you do not have to say how large the vector will be.

b. Any two objects can be in the same vector.

Recall that we deal with an array, it is an array of a certain type. For example, we can have an array of Strings, all members of which have to be Strings. This flexibility in vectors leads to a kind of polymorphism (many, again, forms). For example, you can have a vector of shapes, some of which are rectangles and some of which are ellipses, ready for drawing on a screen. We will see another way of bringing together different shapes in Chapter Five.

You should now turn to Laszlo and read Chapter 4.3 and do exercises 4.21 and 4.22. In that section you will learn about Vectors and PolyLines as instances of objects composed of an indefinite number of other objects.

4.4 Invariants

The next section of Laszlo—section 4.4—concerns ways of specifying properties of representations of types. The section also contains a definition of the class EllipseGeometry, which has already been used in our implementation of Ball and Laszlo’s implementation of Point.

The Laszlo section ends with an implementation of rational numbers. Recall that a rational number is a number that can be written as a quotient of two integers, like 3/5 or 3443.4329 for example but not like . Rational numbers are, therefore, generally represented by pairs of ints. However, care must be taken because different pairs represent the same rational: for example 2,3 is the same as 4,6. There are various approaches to dealing with this. The one taken by Laszlo is to have a unique representation for each rational: the rational is represented by a fraction in lowest terms, so that the (2,3) pair represents a rational, but (4,6) does not. The way this is implemented is to have the constructors turn a representation into lowest terms. Whenever any computation is done, a constructor is called at the end to create a new rational that the constructor will ensure is in lowest terms. By implementing the operations in this way

5

Page 6: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

you can be certain that the resulting representations will satisfy the condition of being in lowest terms. Being in lowest terms is an invariant property of the representation of rationals.

An important observation was made in passing two sentences ago. When computations are done using a rational, a new object is created. In other words the operations do not alter the rational itself. The objects of such classes are said to be immutable. It makes more sense to speak of equality of immutable objects because, once two such are equal they stay equal.

Laszlo 4.4 also describes up the important notion of the state of an object. The state of an object at a particular moment is the value of all of its datafields.

You should now read Section 4.4 of Laszlo and do exercises 4.23 and 4.26.

4.5 Interacting with Pictures

The graphics applications developed so far have been self-running: for example, the PaintManyRectangles just paints itself. Many real-world applications involve the possibility of interacting with the graphics. You will learn later—in Chapter Seven—how to develop programs that can be interacted with using graphical interfaces. In Section 4.5, we will see how to interact with a program by typing into the windows console. In this section, there is the first example of such a system: a splattering points game. The game allows you to choose a bounding rectangle, a colour, and to drop spots into the bounding rectangle.

In Laszlo, the splattering points game is developed and then the reasoning is abstracted to produce a template that can be used to make other interactive programs.

You should now read Section 4.5 of Laszlo and then come back to the Subject Guide.

The interesting part of the PlaySplatterPoint class is the class defined within it for dealing with the input. It is defined to be a child class of thread so it runs independently of the main thread.

1. class PlaySplatterPointsController extends Thread {

2. public void run() {3. ScanInput in = new ScanInput();4. Color currentColor = Color.white;5. RandomPoint rand = new RandomPoint();6. while (true) {7. try {

a. System.out.print("? ");b. String s = in.readString();c. int x, y, w, h, r, g, b, n;d. switch (s.charAt(0)) {e. case 'r': // rectangle x y width heightf. x = in.readInt();g. y = in.readInt();h. w = in.readInt();i. h = in.readInt();j. rectangle.setPosition(new PointGeometry(x, y));

6

Page 7: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

k. rectangle.setWidth(w);l. rectangle.setHeight(h);m. break;

….n. case 'n': // new n

(i) n = in.readInt();(ii) for (int i = 0; i < n; i++) {(iii) points.add(rand.nextPoint(rectangle));(iv) colors.add(currentColor);(v) }(vi) break;(vii) case 'c': // color r g b

Notice that the reading is defined in a try block because there may be an io exception. Recall that the switch/break mechanism in line d allows you to have several different choices of what will happening, depending on the input s.charAt(0). For example, in case r you read 4 integers to make a rectangle (they are the upper left corner and then the width and height); in case n you use a loop to add n points randomly within the rectangle.

To use this class: follow the instructions from your level one programming course about compiling and running Java programs from the windows or unix console. You will need to set the PATH and CLASSPATH variables. You will also have to add banana.jar to the CLASSPATH, treating it as if it were a folder.

If you have trouble with then consult the course website:

www.mcs.gold.ac.uk/~mas01rmz/CIS212/External/Index.html.

When the program is running you will be able to type into the console. Type r and then 4 numbers and then n and another number and so on.

Now return to Laszlo and do exercises 4.31 and 4.32.

4.6 Summary of the Chapter

Chapter Four is about Composition, which is one of the two principal techniques for redeploying classes. The idea is that you have a composite class that has other classes as components. Objects of the composite class own objects of the component classes in the sense that they have total control over them and when the composite dies it takes the components with it. We saw an example of this, which was a class for drawing many rectangles on the screen. The class has components that include a random rectangle class and a random colour class. Rectangles (in terms of their positions and size) and fill colours are chosen randomly. We also saw a PolyLine (like a graph or an open polygon) as a class composed of several Points. There was also a discussion of invariants that are satisfied by the representations of certain classes: the two examples given in the chapter are rationals that are represented by fractions in lowest terms, and ellipses. The chapter finished with another step in the move towards graphical programming: pictures with which you can interact. A simple game was developed as a first example, and this game was then abstracted to form a template for this kind of application. The template is an instance of composition because it consists of an ApplicationFrame that has a controller as a component.

7

Page 8: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

Examinable things to take from the Chapter:

Composition and Aggregation

Random Values

PolyLines

Representation Invariants

Graphical Interaction

8

Page 9: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

5 Inheritance

This chapter discusses the different ways of using inheritance to build object-oriented models. Again, the main applications are graphical.

5.1 Uses of Inheritance

Inheritance, the ability to build up classes so that they inherit behaviour from their parent classes, is one of the two cornerstones of object orientation. The other is the ability of objects to send each other messages. There are essentially three main uses of inheritance, two of which we saw in Chapter One. The first of these is inheritance for extension, in which the child class has all the same behaviours as the parent class, plus some more. In Chapter One, we saw moving balls as children of balls. The second use of inheritance is inheritance for specialisation, in which one or more methods or datafields are overridden. In Chapter One, we implemented balls that both moved and drew themselves as a specialisation of balls that just moved. The other use of inheritance that you will study in this chapter is inheritance for abstraction, which enables you to define classes without necessarily implementing every method.

5.2 Extension

The main application of inheritance for extension given in this Section 5.2 of Laszlo is that of Transformable points. This is parallel to our example of movable Balls, where the ability to move was added to the other abilities of balls. Here, the ability to be transformed is added to points.

The two transformations involved are rotations are enlargements (or scalings). To scale a point is just to translate it so that its new distance from an anchor point is the scale factor times its old distance from the anchor point and it is in the same direction. (If the scale factor is negative then the transformed point will be on the other side of the anchor, but the anchor, the old point and the transformed point will still be collinear. With a point this is nothing but a translation. However, if you have three points making up a triangle and you enlarge them by a factor of two, you will end up with not only a translated (that is, moved) triangle, but also one that is twice as large.

It will be helpful in reading this section of Laszlo, if you understood radian measure.

Radian Measure: Most of us are used to working with degrees measured in angles. However, mathematicians, physicists, and engineers tend to measure angles in radians instead. Java takes this second view of angle measures.

Suppose we had an angle called by the Greek letter theta (written ; note that angles are frequently called by Greek letters). Its radian measure is defined as follows: Suppose we put the angle at the centre of a circle of radius 1, as in the picture below.

9

A

B

Page 10: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

Then the radian measure of the angle is the measure of the arc of the circle that goes from A to B.

What is the relationship between degrees and radians? If were the whole of the circle it would measure 360 degrees, and the arc would be the whole circumference, which is 2 (that’s 2 r, with r=1). Therefore radians is equivalent to 180o.

The other new class developed in this section is one that represents lines. It inherits from the line segment class that you should have implemented as an exercise in Section 3.2. You may wish to go back and refresh your memory about it. The extension is that, since lines cut the surface into 2 parts, we can classify every point in the plane (or on the screen) as being to the left or the right of the line.

You should now read Section 5.2 of Laszlo and come back to the subject guide.

Task: Make a project called Chapter5Geometry and add TransformablePointGeometry, TryTransformablePointGeometry, and PaintCirclePoints. Study the code for each carefully, and then experiment with them.

Task 2: Make another project called Chapter5Counters and add NStepCounter and ClearableCounter. Experiment with these too.

Exercises: Do exercises 5.6 and 5.7 in Laszlo.

5.3 Specialisation

In this section, you will learn about inheritance for specialisation. The idea is that the child class will do at least one of its activities differently from its parent, and presumably, therefore, most of its brothers and sisters. We spoke in Chapter One, for example, of a platypus that lays eggs and therefore gives birth to children in a very specialised way as far as mammals are concerned.

The main application in the section is an implementation of polygons that inherits from PolyLines. You may wish to refresh your memory of PolyLine by rereading section 4.3 of Laszlo. The difference between the two is that a polygon is closed off by connecting the last vertex to the first.

That is where the following might be a PolyLine:

The associated Polygon would be:

10

Page 11: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

This is both an inheritance for extension and an inheritance for specialisation. The specialisation involves such things as the computation of the number of edges, which will give a number one greater than the computation for the equivalent PolyLine. The extension comes from fact that Polygons have a notion of inside and outside, so that points can be classified as being either within the polygon or not. This turns out to be more troublesome than you might have imagined. In a simple figure, like the one we have just drawn, there is no problem. Where it gets tricky is when the edges of the polygon cross each other. In that case, different sensible rules come up with different answers. The rules for determining inside and outside are called winding rules and are discussed in detail in the text.

You should now read Section 5.3, where you will learn about inheritance for specialisation, polygons and two different winding rules for determining the interior of a polygon.

Task: Now add PolygonGeometry to your Chapter5Geometry project and TallyCounter to Chapter5Counters and experiment with both.

Do exercises 5.12 - 5.14

5.4 Specification

The next section of Laszlo is about abstracting from classes to make specifications. The word “abstract” comes from the Latin abstrahere, which means to draw away. In this case we think about drawing out essences of classes and essential similarities between several classes and encapsulating them in a new more abstract class.

The idea of inheritance for specification is that classes, or their interfaces, can be spoken of separately from all, or part, of their implementations. Sometimes this is used to speak about classes before they are implemented; sometimes this is used to make a coherent, flexible structure of classes that are already implemented.

There are two mechanisms in Java for this: abstract classes and interfaces. In both cases you write specifications for the methods and fields for classes that will inherit from the abstract classes and make them more concrete. In abstract classes some methods may be implemented; in interfaces none will be. You cannot instantiate (that is, make objects of) abstract classes or interfaces because the object would sometimes not know what to do.

This allows us some degree of multiple inheritance, in which a class would have more than one parent. In some object-oriented languages you can have several; in Java you can have one parent and, you might say, several step-parents: you can inherit from one class and you can implement any number of interfaces. However, you do not inherit any behaviour from the interfaces: you only inherit the responsibility to implement everything the interface says you will. It is useful to do this for two reasons: it is a safety measure to make sure you have implemented all you need and it provides flexibility. The flexibility comes from the fact that you can supply an object as an argument to a method if the method’s input is of the object’s

11

Page 12: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

class, or of a class from which the object’s class inherits, or is of an interface that the object’s class implements.

In this section of Laszlo, several abstract geometrical classes are developed that are abstractions of classes you have already seen. The abstract classes will bring out similarities between related classes: for example, a RectangularGeometry class is defined to bring out what is the same in RectangleGeometry and EllipseGeometry. This process of finding the abstract similar structures of already established classes is called factorisation. We will see that this will allow us great flexibility in terms of polymorphism. The abstraction that led to RectangularGeometry is then carried further to Geometry in general.

You should now read Section 5.4.1 and 5.4.2 of Laszlo, and do exercise 5.1. Then read the rest of the section and do exercises 5.19 and 5.20

5.5 More on Polymorphism

In this section you will learn about polymorphism, which allows you to do the following two things:

a) Group objects of different classes, as if they were of the same class

b) Make methods that are much more generally applicable than just to one class.

The first could be, for example, an array of geometric objects of different kinds,—ellipses, rectangles, points, etc—which can all be put in the same array by making it a Geometry array, instead of Rectangle array. We might, then, add that array of objects to the Bouncing Ball application to form obstacles of different shapes. At each move step, instead of just checking whether you hit a wall, you would have to loop through the array to see which, if any, of the obstacles you are going to hit.

The second benefit of polymorphism—the generality of the methods—is treated in Laszlo 5.5 in the form of generable-purpose sorting procedures. The sorting procedures we have seen up to now are each for one type of thing, either ints or Strings. Here you will see a sorting procedure designed for any class that allows you to compare elements. To use it, though, the class would have to be declared to implement the Comparable interface. Recall that implementing is to interfaces what extending is to classes.

You should now read Laszlo sections 5.5.1 and 5.5.2 then do exercise 5.23, and then return to the subject guide.

15.5.2 The substitution principle

There are, in all this flexibility of inheritance hierarchies, hidden dangers. When you send a message to an object you may be mistaken about its class in the following sense: the object may well be implemented as a sub-class of the class you are expecting. To take an example outside of the computing domain, you may think of Spot as a dog, while he may be classified in your system as a basset hound. A basset hound is a type of dog, so there should be no problem. Trouble may arise though if one of the Dog methods has been overridden for basset hounds. Suppose, for example, that basset hounds did not bark but bleated like sheep instead.

12

Page 13: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

Then when you send your makeNoise message to Spot, thinking of him as a dog, he will bleat like a sheep (or a basset hound) and will not frighten a burglar away.

To avoid problems it is very important that when a sub-class overrides a method, the new method at least keeps to the contract of the old method. Remember that the contract is written in terms of pre-conditions and post-conditions.

To be sure that the overriding class satisfies a pre-condition/post-condition contract, you must:

a) require no more in the pre-condition than the original method

b) produce at least the post-condition of the original method

You should now read the rest of 5.5 and do exercises 5.24 and 5.27.

5.6 Figures and Painters

In this section a new composite object is introduced. It is called a Figure and it consists of both a Geometry (a shape really) and a way of painting itself on the screen, called a Painter. Both Geometry and Painter are interfaces. You have seen Geometry in several guises already, but this is the first time you will have met Painter.

The Figure only has one real capability: to paint itself. The class definition consists of several constructors, getters and setters, and the one active method, which is paint(). Each Figure will respond to a paint message by painting itself on the screen. So if you have an array of Figures, you can traverse the array, painting the figures one by one.

Laszlo Section 5.6 defines two concrete classes that implement the Painter interface: FillPainter and DrawPainter. DrawPainters draw (or stroke) the outline of the figure; FillPainters fill in the inside.

You should now go to Laszlo, read up to the beginning of Section 5.6.3 and then do exercise 5.28 and 5.3. Then return to the subject guide.

It is not uncommon to want both to draw something and then to fill it in: the class that helps here is called MultiPainter. A MultiPainter is an aggregation (similar to a composition but weaker—see beginning of Chapter 4 if unsure) of two Painters. Typically we would have one DrawPainter and one FillPainter. However, since each of these Painters can be a MultiPainter there is really no limit to the number of Painters you can use in the same MultiPainter object. There is an example, on page 251 of Laszlo, of a MultiPainter that consists of one FillPainter and two DrawPainters: the effect is to have two outlines of different colours and widths and one for filling in the centre.

You should now read Laszlo 5.6.3 and do exercises5.33, 5.34 and 5.35, and then return to the subject guide.

Now read the rest of the section, and add PaintPolygonwithPainter.java to your Chapter5Geometry project. This is the answer to exercise 5.33 Run the program, by right clicking on the class and choosing the main method with an even number of Strings that are amenable to being turned into ints, like “232”.

13

Page 14: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

5.7 Summary of Chapter

Chapter Five was about inheritance, which is the second principal technique for redeploying classes. We saw that the three main reasons for using inheritance: inheritance for extension, inheritance for specialisation, and inheritance for abstraction. We saw two or three applications for each of these, including one graphical application. In inheritance for extension the child class adds new behaviour to the behaviour of the parent class: we saw transformable points as an instance of that. Transformable Points have all the behaviour and attributes of Points plus the added ability to be scaled and rotated. These abilities enable them to be used in Affine transformations later in the course. In inheritance for specialization, the child class does something differently from its parent. We saw polygons as an instance of that: polygons inherit from PolyLines, but respond differently to some methods. In inheritance for abstraction we have some parent classes that are not completely implemented but get to the heart of the abstract similarities of several classes. We saw Rectangular Geometries as an abstraction of RectangleGeometries and AbstractGeometries as an abstraction of that. We then saw one of the great benefits of an abstraction hierarchy: polymorphism. Two classes that have an abstract parent in common, or that both implement the same interface, can be joined in the same collection classes; they can also respond to some of the same messages, and can be arguments to the same methods. In Chapter Five we saw an interesting case of this in which a Comparable interface was defined. Any class with a notion of less than or equal to can be declared to implement the Comparable interface. In the chapter, a sorting procedure was developed that works on any class that implements the interface. In this way we can write just one sorting methods and use it to sort arrays of ints, Strings, Rationals,… The chapter finished with a discussion of figures and painters. A figure is a shape plus a painter. The shape knows the outline of the figure, and the painter knows how to paint it on the screen. The chapter presented an inheritance hierarchy for painters. Painter, for example, has two sub classes: DrawPainter and FillPainter. The former strokes the boundary of the shape; the latter fills in the interior.

Examinable things to take from the Chapter:

Uses of Inheritance: Extension, Specification, and Abstraction

Polymorphism

Figures and Painters

14

Page 15: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

6 Design Patterns

6.1 Uses of Design Patterns

The twin purposes of object-orientation are to structure large systems and to reuse solutions and partial solutions from your own other work and from others. Of course it would be illegal and immoral to either take other people’s code without permission or to try to pass somebody else’s work as your own. However, it is increasingly the case that software development includes re-using your own code, re-using other people’s code from within your design team, and deploying off-the-shelf components that have been supplied by a major commercial vender, such as Sun.

The two ways we have studied so far for building up application are composition, in which classes can be defined once and brought together in different ways to make different applications, and inheritance, where a class is extended in different ways to make different more powerful and/or more specialised classes from the same core. Design Patterns take the imperative of reuse to another level. Here you are less concerned with reusing pre-defined classes (though some of the implementation works this way) than you are with reusing ideas, concepts, and solution plans.

The advent of Design Patterns is perhaps the most powerful and exciting new idea to come along in software development in the last several years. It enables people to think about software designs as concrete blocks and gives people a language to talk about software at a high level of abstraction. It is also in common use in software design, both academically and commercially.

In this chapter you will learn about three design patterns and then be briefly exposed to a few others. The first one you will learn about is called the Iterator Pattern.

6.2 Iterator Pattern

Iteration means doing things repeatedly. Iteration is one of the things that computers have always been good at. Loop structures implement iteration. We have seen many examples of iteration already: the two main ones have been ints when we go through a loop adding one to a counting variable each time we go through the loop (one time through the loop is frequently referred to as an iteration through the loop), and arrays, where we go through the array doing something to a[0] and then a[1] and so on.

In Java there is an interface, called Iterator, which specifies what you need to be able to implement the iterator pattern on a class. The requirements are: a notion of what it means to be the next element, a way of knowing you have got to the end of the structure, and a way of removing an element. Vectors implement this interface; arrays do not but they can be treated as lists that do.

This section is a development of an application of the pattern to deal with dynamic polygons. Recall that we started with PolyLines, which are just vertices and edges between them. We

15

Page 16: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

then moved onto Polygons, which inherit from PolyLines, but close off the structure by connecting the last vertex to the first. We are now moving on to DynamicPolygons, which have the added ability of being changeable after they have been defined. We will see in Chapter 7 how useful this is in drawing pictures in real time.

See Figure 6.1 in Laszlo to see how the application fits together. The main class is DynamicPolygonGeometry, which can be composed from any number if Vertices. A Vertex is a Point with datafields representing the next and the previous vertex: that is why you can see that Vertex is a composite of one PointGeometry and two vertices So what we have there is an polygon with an order on the vertices. As well as that the DynamicPolygonGeometry is aggregated of any number of Iterators: these are of instances of a class called DynamicPolygonIterator, which implements the Iterator interface. The iterators give us ways of iterating through the vertices of the polygon. They also give us ways of removing vertices. On top of that, we will also have methods for adding more vertices. In the next bit of reading from the text you will learn about the specifications and implementations of two classes: DynamicPolygonGeometry and of Vertex.

You should now read up to and including 6.2.3 and then come back to the subject guide.

16.2.2 DynamicPolygonGeometry:

A dynamic polygon is a polygon that can have new vertices inserted and old vertices deleted at runtime. Clients interact with dynamic polygons via polygon iterators, which implement the PolygonIterator interface. An example of the use of the iterator is given in the following segment from the class definition:

1. public void translate(int dx, int dy) {8. PolygonIterator iter = new DynamicPolygonIterator(this);9. for (int i = 0; i < iter.nbrVertices(); i++)

{a. iter.moveBy(dx, dy);b. iter.next();

} }

Notice that we are using the next() method in the iterator to decide what comes next. Another method that works like this is shape():

1. public Shape shape() {10. GeneralPath path = new GeneralPath();11. PolygonIterator iter = new DynamicPolygonIterator(this);12. PointGeometry p = iter.point();13. path.moveTo(p.getX(), p.getY());14. for (int i = 0; i < iter.nbrVertices() – 1; i++) {

a. iter.next();b. p = iter.point();c. path.lineTo(p.getX(), p.getY());d. }

15. path.closePath();16. return path;

}

This just says that the shape of the polygon is the path that consists of line segments that connect vertices to vertices following the ordering that comes from the iterator.

16

Page 17: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

The methods that really differentiate this from previous versions of polygons are those that allow you to insert and remove vertices. The insertion method is given below:

1. protected Vertex insertAfterVertex(Vertex v, PointGeometry newPoint)

{a. Vertex newV = v.insertAfter(newPoint);b. nbrVertices = nbrVertices + 1;c. return newV; }

Notice that the way this works is to invoke the insertAfter method from Vertex, which leads to the next discussion.

Vertices

A Vertex is represented by three items of data: a PointGeometry object, p, that represents the position of the vertex and two other vertices: one that will be predecessor or previous vertex (given my prev()) to the present one and the one that will follow it (given by next()).

A Vertex can be pictured by:

Initially, you create a vertex that is its own successor and predecessor. This leads to a rather confusing constructor:

1. protected Vertex(PointGeometry p) {

d. point = p;e. next = this;f. prev = this;

}

Lines b and c say that when you make the vertex you start by defining the vertex itself as both its predecessor and it successor. This initially constructed vertex corresponds to the following picture:

You then build things up by inserting Points after already existing vertices.

1. protected Vertex insertAfter (PointGeometry p)

17

p

next vertexprev vertex

p

Page 18: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

{g. Vertex newV = new Vertex(new PointGeometry (p));h. Vertex prev = this;i. Vertex next = this.next();j. newV.prev = prev;k. newV.next = next;l. prev.next = next.prev = newV;m. return newV;

}

In Line a, you make a new Vertex out of a Point. Recall this means that you need to say what comes before and after it. The constructor invoked in line a will make both of these initially the vertex itself. But then this changes in the next 4 lines. This is very difficult to express in words so you are much more likely to understand this by reading the code, but here is an attempt at explaining it: lines b and d between them takes the present vertex and turns into the vertex that is previous to the one being inserted, (that is, the new vertex will come just after the one we are in); lines c and e between them takes the vertex that is presently the one after the present one and make it the one after the inserted one (that is, we are squeezing the vertex in between the present one and its successor). Both of these are reiterated in Line f where what is now the previous and next vertices of the new one have their appropriate fields updated.

The Section also includes a discussion of the PolygonIterator interface and how to use it and how to implement it. The applications discussed in the Laszlo section are translating the Polygon, which is done by using the iterator to allow you to go through all the vertices moving each in turn and the other is a method for building a regular polygon. Recall that a regular polygon is one all of whose sides and all of whose angles are the same size; for example a square is a regular quadrilateral.

You should now do the following exercise from Laszlo: 6.7-6.9, 6.13, 6.16 and 6.17

6.3 Template Method Design Pattern

The second Design Pattern is called the template method pattern. The purpose of the Template Method design pattern is to define a computation as a fixed sequence of steps but have one or more of the steps variable. In Java what this comes down to is to have a class that is mostly concrete but with one or more abstract methods. The abstract methods represent the piece that has to be slotted into a template to make a whole.

Suppose, for example, that you have an induction procedure that is almost the same for all new employees, but differs in respect of what room they report to. One way to do this would be to have an induction procedure for the Employee class that includes an abstract method called ReportToRoom. The abstract method will be overridden by a concrete method in the classes for each type of employee and the concrete method will include the proper room.

The application developed in Laszlo 6.3 is that of Boolean geometry. There are three binary Boolean operations that can be performed on Shapes:

i. Union or And of the two shapes: includes everything that is in either shape

18

Page 19: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

The shape above is made up of the union of two ellipses

ii. Intersection of the two shapes: includes everything that is in both shapes

iii. Subtraction of the two shapes: A-B includes everything that is in A but not in B: as in the shaded part of the following diagram (where A is the figure on the right):

Many interesting shapes can be built up from performing these operations on simple shapes. The way the Template Method Pattern gets applied in this Section is by way of an abstract class called BooleanGeometry. Objects of the class will consist of two AreaGeometries that are brought together using one Boolean operation. It is important to note that, since BooleanGeometry implements AreaGeometry, the two geometric objects brought together may well have been composed of two geometries and brought together by Boolean operations. In effect a BooleanGeometry may involve any number of shapes brought together with Boolean operations. The reason the class is abstract is that we are deferring the decision as to which operation will be implemented to subclasses.

This is implemented by having an abstract applyOp method that, for example, gets implemented as applying intersection in the sub-class that is an IntersectionGeometry.

You should now read Section 6.3 and do exercises 6.21-6.26. Note that for the last question you may wish to use the Windows Console.

6.4 The Composite Design Pattern

You should be quite comfortable by this point with the notion of a composite object: that is an objects that contains other objects whose existence depend on that of the composite object. For example, a drawing may be composed of graphic primitives, such as lines, circles, rectangles, text, and so on.

The idea of the Composite pattern is that it allows you to manipulate composites exactly the same way we manipulate primitive objects. For example, graphic primitives such as lines or text must be drawn, moved, and resized. But we also want to perform the same operation on composites, such as drawings, that are composed of those primitives. Ideally, we'd like to perform operations on both primitive objects and composites in exactly the same manner, without distinguishing between the two. If we had to distinguish between primitive objects

19

Page 20: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

and composites to perform the same operations, our code would become quite complex and difficult to implement, maintain, and extend.

The idea is really that of a tree, where nodes are either leaves or a conglomeration of subtrees. You should be familiar with such trees. For example, the windows folder hierarchy is one: files are leaves and folders are non-leaf nodes; folders can contain any number of other nodes, some of which may be files (or leaves) and some of which may be other folders. The main example in this section is that of building up pictures—using the composite pattern—as scene graphs (which are exactly this kind of tree).

The general class diagram for the Composite Design Pattern is given below:

Figure 6.23 in the book shows a version of this picture for the composite drawings developed in this section. In the example, the leaves are Figures and the Composite (like Folders in the Windows hierarchy) are called GroupNodes

You should now read Section 6.4.1 and then come back to the subject guide.

Note that the implementation we have seen is a new interface called Node, and two new classes: Figure and GroupNode. Node is a small interface: to implement Node all you need to be able to do is paint yourself. We have seen Figure before, and the only new thing here is that it is declared to implement Node. GroupNode is implemented as a Vector, with ways of adding and removing child nodes. The paint() method for a GroupNode uses an iterator to traverse the vector, painting each component in turn. In Section 6.4.2, a pair of axes is developed using the Composite Design Pattern.

You should now read Section 6.4.2 do exercise 6.28, and then come back to the subject guide

In section 6.4.3 a new concept is developed that allows objects to carry around their own co-ordinate systems. The coordinate systems can be translated, rotated and stretched, changing the position, orientation and size of the shape. This has several useful effects: you can, for example, easily make rectangles that are skewed by rotating or scaling the co-ordinate system for a standard horizontal-vertical rectangle. Another use of this method is that you can have the same figure appear several times by just having the same description on different co-

20

Page 21: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

ordinate systems then all the figures can be updated at once, and you can just choose the co-ordinate system that makes your thinking about a shape easiest.

This is implemented by introducing a new class, called TransformGroup, which is defined as a child of GroupNode. A transform group object will have an AffineTransform—a combination of rotating, stretching and shrinking—,which can change during the life of an object. The AffineTransform determines the co-ordinate system for the composite figure; therefore, with each change to the AffineTransform there is an effect on the position, orientation, and size of the figure.

You should now read the rest of Laszlo Section 6.4 and do exercises 6.31 and 6.32

6.5 Classifying Design Patterns

The last section of Laszlo Chapter 6 briefly describes some other Design Patterns: The Factory Method Pattern, which concerns creating new Objects; The Adaptor Pattern, which alters the interface of an object; The Observer Pattern, which is used to inform interested objects when an object changes its state; and The Strategy Pattern, which is related to the Template Method Pattern.

We will see in Chapter 7 that the Observer Pattern is a very important one in Java graphics: it is the way that graphical user interfaces (GUIs) are implemented, so we will go through it very briefly. The idea is that there is a subject class that is being observed by a set of other classes, known as observers. The Subject class keeps track of its observers and provides means for classes to register and de-register as observers. When the Subject’s state changes, it notifies all of its observers using its notifyAll method.

You should now read the rest of Laszlo Chapter 6

6.6 Summary of Chapter

This chapter was about Design Patterns. Design Patterns are ways of encapsulating useful ideas behind program design. Design Patterns provide a language for talking about high-level designs as well as a way of reusing high-level thinking. In this Chapter we saw three patterns treated extensively with applications to graphics. The three patterns are: the iterator Pattern, the Template Pattern, and the Composite Pattern. The first of these involves going through the same process repeatedly with different inputs. We saw how this is implemented in Java as an interface. Objects of any class that implements the interface (and all you need is a notion of next thing a way of checking if you are at the end and a notion of removing things) can be treated systematically iteratively. We saw of this in a class called DynamicPolygonIterator that implements Iterator and is used to manipulate DynamicPolygons. The Template Pattern allows you to defer some part of a process that gets filled in differently by different instances. We think of the not-quite-finished implementation as a template that is ready to have the specific instance slotted into it. The chapter gives an example in terms of Boolean geometries. In that example it is the Boolean operation that slots into the template. The third pattern—the composite pattern—is used to make hierarchies of containment. These work like file systems in Linux or Folders in Windows: A Folder is at the top of the Tree (this is your home directory for example, or your C drive) and every Folder contains Folders and Files. Files are at the bottom and do not contain Folders or Files. In this chapter, we saw how to use

21

Page 22: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

this idea to represent pictures that are composed of other pictures. In this chapter, some other patterns are briefly introduced, including the Observer Pattern, which involves objects watching other objects. When the observed object changes in any way, all of the observers are informed and some of them will change accordingly. We saw later, in Chapter Seven, that the Java event model is an instance of this pattern. In that case, the observers are called listeners, and they listen for GUI events, such as mouse clicks.

Examinable things to take from the Chapter:

The notion of Design Patterns

The Implementation and uses of the Iterator Pattern

The Implementation and uses of the Composite Pattern

The Implementation and uses of the Template Pattern

Boolean Geometry

Dynamic Polygons

Composite Pictures

22

Page 23: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

7 Framework and GUIs

In this chapter much of the work of the course comes together. This is true of the application domain of graphics: many of the ideas we have seen, such as dynamicPolygons, will get used in interesting applications. It is equally true of the object-oriented techniques: many of the concepts and mechanisms for structuring systems and reusing code will find full application in these graphic examples.

The chapter begins with a section about the Java Event Model. Most Java applications are driven by events. Events are triggered by user interactions, such as pressing a button or typing in a box, and then handled by the system, making the computer responsive to user actions.

7.1 Frameworks and GUIs

Frameworks provide another layer of reuse: they are bigger and more specific than design patterns. They are bigger in the sense that they include patterns as part of the solutions; they are more specific in that they are tied to a specific language. Frameworks can be a very powerful tool because when you use a framework a great deal of your application has been written before you get to it. You then take the general framework and tailor it to your needs by a combination of composition and inheritance. We have already seen some of this in action. Laszlo’s ApplicationFrame class inherits from Java’s JFrame class, which is part of the Java Graphics Framework. Because of that we have been able to draw on a lot of inbuilt functionality. For example, in the second version of the bouncing ball we could rely on the ApplicationFrame getting the drawing surface and the repaint() method to call the paintComponent method and create a looping structure.

The other thing that is discussed in this section is the distinction between AWT and Swing: these are two different sets of components for Java graphics, though in some sense the latter is built as a helper rather than a replacement for the former. AWT was the original Java graphics environment and was designed to call the underlying operating system’s graphical components. In consequence, AWT applications look different in different operating systems. Swing was added later and uses its own components, which are the same on all operating systems. The Swing library is also considerably more extensive than the AWT one. One thing to note is that when component names begin with a J than they are swing components: e.g. Panel is an AWT component; JPanel is a Swing component.

This Chapter is about Java’s graphical framework.

Now read Laszlo Section 7.1 and come back to the subject guide.

7.2 Events in Java

Event handling in Java is implemented using the Observer Pattern. Recall that in that Pattern you have a set of objects that observe a particular object called the Subject Class. Whenever things happen to change the state of the Subject Class, the Observers are informed and some of them will act on the information.

23

Page 24: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

In the Java event model the Subjects are known as event sources. They include objects that represent the user interface components with which you can interact: such as buttons on the screen and text boxes in which you can write. When you do interact with the components, a new object is created. The new object is called an event object and it contains information about the event: this information includes what kind of event it was—for example a mouse click—and where on the screen the event occurred. The event object is sent (by the event source) to all of its observers, which are called event listeners. The event listeners may do things in return.

To get a feeling for this, we will consider a very simple example. In the example, we will build an application frame with a red button, a yellow button and a text field. When the red button is pressed the following message will appear in the text field: “You have pressed the red button”. A similar message follows pressing the yellow button. The code for this application is in your Chapter 7 folder. It is called TwoEventExample. You may wish to make a project, add this class, compile and run it.

The way the code works is that we will make the frame registered to receive updates about mouse events on the buttons.

1. public class TwoEventExample extends ApplicationPanel implements MouseListener

The Class has to implement the Listener interface for the kind of events it will be listening for: in this case Mouse events. We will need to register TwoEventExample, as an observer (a listener) for the button mouse events. Only MouseListeners can be so registered. The Frame will then handle the event by sending the appropriate message to the TextField.

17. static JButton myRedButton;18. static JButton myYellowButton;19. static JTextField myTextField;

Here the members have been declared that represent each of the objects we need.

20. public TwoEventExample() {a. setBackground(Color.black); }

This is the constructor.

21. public static void main(String[] args) {a. ApplicationPanel panel = new TwoEventExample();b. ApplicationFrame frame = new

ApplicationFrame("TwoEventExample");c. frame.setPanel(panel);d. panel.makeContent();e. frame.show();}

There is nothing new here. If you have trouble understanding this, reread section 3.2 in Laszlo and in the subject guide.

24

Page 25: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

22. public void mouseClicked(MouseEvent e) { a. if (e.getSource() == myRedButton)b. {myTextField.setText("You have pressed the red button");}c. if (e.getSource() == myYellowButton)d. {myTextField.setText("You have pressed the yellow

button");}e. repaint(); }

This is the interesting part: when the frame hears a mouseclick it checks it’s source by sending an appropriate getter message to the event: getSource(). It then acts on the answer by sending a message to the myTextField.

23. public void mouseEntered(MouseEvent e) { }24. public void mouseExited(MouseEvent e) { }25. public void mouseReleased(MouseEvent e) { }26. public void mousePressed(MouseEvent e) { }

Since the Class is implementing MouseListener, you need to implement all of the methods of MouseListener, even if the implemented behaviour is to do nothing.

27. public void makeContent() { a. myRedButton = new JButton("Press Me");b. myRedButton.setBackground(Color.red);c. this.add(myRedButton);d. myRedButton.addMouseListener(this); e. myYellowButton = new JButton("Press Me");f. myYellowButton.setBackground(Color.yellow);g. this.add(myYellowButton);h. myYellowButton.addMouseListener(this);i. myTextField = new JTextField("",30);j. this.add(myTextField);

}This adds the components to the Frame. Notice that 12a is calling on a constructor in JButton that has one String argument; the String will be the label of the button. In 12d the ApplicationFrame (“this”) is added as one of the listeners (this one is listening out for mouse activities) to the button.

28. public void paintComponent(Graphics g) {a. super.paintComponent(g);b. Graphics2D g2 = (Graphics2D)g; c. }

}

You should now read section 7.2 in Laszlo and then come back to the Subject Guide

25

Page 26: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

17.2.2 Clicking and editing Points

Throughout Section 7.2.2 of Laszlo, a small application for editing points and rectangles on the screen is developed. You should make a new Project, called Chapter72 perhaps, in which you will add the classes (from the Chapter 7 Folder from your CD) as we go along. The first class to add is called ClickPoints and is an editor for adding points to and removing points from the screen. It differs in interface to the example we have just done in that there are not separate buttons. When you click on the screen, a point is either added to or removed from the position where you clicked.

The class is discussed extensively in the book, so we will just mention a couple of things.

1. public class ClickPoints extends JPanel implements MouseListener {

What we are defining is a panel that is listening for mouse clicks

29. protected Vector figures;30. protected RandomColor rnd;

The vector will contain the points, which are treated as Figures from which Points inherit. This will make the code easier to generalise later.

31. public static void main(String[] args) {

a. JPanel panel = new ClickPoints();b. ApplicationFrame frame = new

ApplicationFrame("ClickPoints");c. frame.getContentPane().add(panel);d. frame.show();

}

This all should be pretty familiar by now. If you have trouble, re-read Section 3.2 in the subject guide and in Laszlo.

32. public CliickPoints() {a. setBackground(Color.black);b. figures = new Vector();c. rnd = new RandomColor();d. addMouseListener(this);

}

This is the constructor: it adds an empty vector, a random color object and a mouse listener.

33. public void paintComponent(Graphics g) {a. super.paintComponent(g);b. Graphics2D g2 = (Graphics2D)g;c. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,d. RenderingHints.VALUE_ANTIALIAS_ON);e. Iterator iter = figures.iterator();f. while (iter.hasNext()) {g. Figure fig = (Figure)iter.next();h. fig.paint(g2); } }

26

Page 27: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

The interesting thing here is the use of the iterator to go through the vector, painting the figures (in this case points).

e. public void mouseClicked(MouseEvent e) { a. Figure clickedFig = findFigure(e.getX(), e.getY());b. if (clickedFig == null) // no figure was clickedc. addFigure(e.getX(), e.getY());d. else e. removeFigure(clickedFig);f. repaint();

}

This says add a figure if there isn’t one and remove one if there is. The method for deciding whether you have clicked on a point or not is given in 12 below.

f. public void mouseEntered(MouseEvent e) { }g. public void mouseExited(MouseEvent e) { }h. public void mouseReleased(MouseEvent e) { }i. public void mousePressed(MouseEvent e) { }

j. protected Figure findFigure(int x, int y) {g. EllipseGeometry disk = new EllipseGeometry(x-3, y-3,

6, 6);h. Iterator iter = figures.iterator();i. while (iter.hasNext()) {j. Figure fig = (Figure)iter.next();k. PointGeometry p = (PointGeometry)fig.getGeometry();l. if (disk.contains(p))m. return fig;

}n. return null;

}

This just looks for a figure close to (within a radius of 3) of the point (x,y). It is used to determine if the click should remove a point (if there is one found using this method) or added.

k. protected void addFigure(int x, int y) {

o. PointGeometry point = new PointGeometry(x, y);p. Painter painter = new FillPainter(rnd.nextColor());q. figures.add(new Figure(point, painter));r. } s. protected void removeFigure(Figure fig) {t. figures.remove(fig);

} }

Now do exercises 7.1 and 7.3

27

Page 28: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

The next class extends this functionality by allowing you to move the points once they are on the screen. You move a point by clicking on it and dragging it with the mouse button down.

Task: Add EditPoints.java to your project, compile it, run it, and add and move points.

The only new part of the code comes from the dragging. We need to define the panel to define a MouseMotionListener to be able to detect that. First notice that in the heading of the class

public class EditPoints extends JPanel {

there is no mention of listeners. That is because there are two internal classes defined later that are acting as particular listeners, rather than the whole class.

1. class EditPointsMouseMotionListener extends MouseMotionAdapter{

34. public void mouseDragged(MouseEvent e) {a. if (clickedFig != null)

{(i) clickedPoint.setX(e.getX());(ii) clickedPoint.setY(e.getY());(iii) repaint();

} }

This is like the mouse motion listener from before

35. class EditPointsMouseListener extends MouseAdapter {

a. public void mouseReleased(MouseEvent e) {

(i) if (clickedFig == null) // no figure was clicked

(ii) addFigure(e.getX(), e.getY());(iii) else if (e.isControlDown())(iv) removeFigure(clickedFig);(v) clickedFig = null;(vi) repaint();

}

This is like the original listener but it handles the button being released. This works better with the dragging.

So in the constructor you have two listeners registered.

addMouseListener(new EditPointsMouseListener()); addMouseMotionListener(new EditPointsMouseMotionListener());

Here is the new event handler:

28

Page 29: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

36. class EditPointsMouseMotionListener extends MouseMotionAdapter{a. public void mouseDragged(MouseEvent e)

{(i) if (clickedFig != null) {(ii) clickedPoint.setX(e.getX());(iii) clickedPoint.setY(e.getY());(iv) repaint(); }

}

All that this is doing is tracking the position of the mouse using a getter to get the mouse position, and using a setter to make it the point position.

The next step is to move to Edit polygons.

Now add EditPolygon and PolygonListener to your project, compile both and run EditPolygon.. You will find the same kind of interface as the point applications, but here when you click you are adding a vertex to a polygon and when you drag a point you are reshaping the polygon. Read through the discussion of the code in Laszlo, paying particular attention to the use of the PolygonIterator in the PolygonListener.

27.2.2 Using a Figure Manager

In this section the points editing application is developed again: this time in a more structured way. The idea is that we have a separate class that manages the Figures of the application, separated from the main program that deals with drawing things on the screen. So there are two classes here (although one of them has some smaller internal classes): EditPointSet and EditPointSetManager. You interact with the former that sends messages and receives information from the latter.

EditPointSetManager: Using the Composite Design Pattern, the set of figures for the drawing is represented as a Node. If you feel unsure about this, go back to section 6.4 of Laszlo. First of all, this implements an interface. The interface is given below:

public interface FigureManager {

1. public void select(Geometry g) throws IllegalArgumentException;2. public Geometry selected();3. public Node getFigures();4. public void updateManager();5. public void add(Geometry g);6. public void remove(Geometry g);7. public Geometry get(int i) throws IndexOutOfBoundsException;8. public int size();9. public Geometry find(int x, int y);

}

Notice that Figures is a Node. There are getters to get the whole Node as a Figure (line 3) and to get particular Geometries (line 7). Line 9 allows us to find a Geometry . In the classes we have seen, this is implemented by clicking near the geometry. Line 4 is an instance of the Template Method: updating can be very different for different applications.

29

Page 30: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

We are now ready to define the EditPointSetManager class.

public class EditPointSetManager implements FigureManager {

1. protected JPanel canvas;2. protected GroupNode node;3. protected RandomColor rnd;

Here we have a JPanel as a component of the manager. The JPanel will be where the figures get painted. The GroupNode is the structure that stores the figures.

4. public EditPointSetManager(JPanel canvas) {

a. this.canvas = canvas;b. node = new GroupNode();c. rnd = new RandomColor();

}

That’s the constructor

5. public Node getFigures()

{ return node; }

6. public void updateManager() {

canvas.repaint(); }

7. public void add(Geometry p) {a. Painter painter = new FillPainter(rnd.nextColor());b. Figure fig = new Figure(p, painter);c. node.addChild(fig); }

Recall that a Figure is a Geometry plus a Painter. Here we take a Geometry assign a Painter to it and add the derived Figure to the node.

8. public void remove(Geometry p) {a. for (int i = 0; i < node.nbrChildren(); i++) {b. Figure fig = (Figure)node.child(i);c. Geometry g = fig.getGeometry();d. if (g == p)

{i. node.removeChild(i);ii. return;

} } }

30

Page 31: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

9. public Geometry find(int x, int y)

{b. PointZoneGeometry disk = new PointZoneGeometry(x, y);c. for (int i = node.nbrChildren()-1; i >= 0; i--) {

(v) Figure fig = (Figure)node.child(i);(vi) PointGeometry point =

31

Page 32: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

(PointGeometry)fig.getGeometry();(vii) if (disk.contains(point))(viii) return point;

}e. return null;

}What is happening here is that you are looking for a Geometry that is near the point (x,y). So we traverse the node looking at figures in turn. We need to extract the Geometry from the Figure to do the test. That is what is happening in b-ii. If you ever get to iv (that is if iii is ever true), you return the answer and exit the computation. Therefore you only get to c if you have failed on every figure.

10. public Geometry get(int i) throws IndexOutOfBoundsException {a. Figure fig = (Figure) node.child(i);b. return fig.getGeometry();

}

11. public int size() { return node.nbrChildren(); }

12. public void select(Geometry g) throws IllegalArgumentException { }

13. public Geometry selected() { return null; }

}

The EditPointSet Class is very like the EditPoints class, except that some of the processing is referred to the Manager.

Return to Laszlo and do exercises 7.7 and 7.8

7.3 Components

The Java swing library of components is very rich. In this section some of it is described. Read Section 7.3. It is important to understand the distinction between components and containers. Study the inheritance hierarchy in Figure 7.5 in Laszlo.

7.4 Layout Managers

Layout managers are an important part of the Java Graphics Framework. The various layout managers arrange your graphical components (sometimes called widgets) on the screen for you. There are three of them discussed in this section: Flow Layout, Grid Layout, and Border Layout. They are all tried out on a simple interface of just a few buttons.

Read Laszlo section 7.4 and then make a project with TryGridLayout, TryFlowLayout, TryBorderLayout . You will find them all in the Chapter Seven Source Code Folder in

32

Page 33: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

your CD. Compile all of them and run them in turn. Then experiment with them by adding some of the components from 7.3 to each of these classes and recompiling and running.

7.5 Event Listeners and Components

This section discusses the kind of application with which we started the Chapter of the Subject Guide: a graphical user interface with components that respond to user inputs. Before reading the section, you should experiment with the application by making a new project, and add ColorPlay.java from the Chapter 7 source code folder. Compile it, run it and experiment with it.

You should now read Section 7.5 of Laszlo to see how the program is designed and implemented.

….1. public class ColorPlay extends ApplicationFrame {2. protected JPanel canvas, controls;

….In line 2, we can see that there are two separate panels that make up the Frame

….3. public ColorPlay(String title) {

a. super(title);b. Container topPane = getContentPane();c. topPane.setLayout(new BorderLayout());d. canvas = new JPanel();e. topPane.add(canvas, "Center");f. controls = new JPanel();g. controls.add(redButton = new JButton("red"));h. controls.add(greenButton = new JButton("green"));i. controls.add(blueButton = new JButton("blue"));j. controls.add(customButton = new JButton("custom"));k. topPane.add(controls, "South");l. addListeners(); m. selectColor(Color.red);

}Here the border layout is chosen with the buttons each added to the controls Panel (g-j), and the controls panel put on the bottom (south) of the pane (line k).

4. protected void addListeners() {

a. ActionListener l = new ActionListener() {b. public void actionPerformed(ActionEvent e) {c. Object source = e.getSource();d. if (source == redButton) selectColor(Color.red);

i. else if (source == greenButton) selectColor(Color.green);

ii. else if (source == blueButton) selectColor(Color.blue);

33

Page 34: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

iii. else selectColor(); } };e. redButton.addActionListener(l);f. greenButton.addActionListener(l);g. blueButton.addActionListener(l);h. customButton.addActionListener(l); }

In line (a), a new action listener is defined and is registered to listen to all the buttons in e-h. The handler is defined in d. The lines d i-ii call the following method:

14. protected void selectColor(Color color) {

i. this.color = color;j. canvas.setBackground(color);k. repaint();

}

More interestingly, line d.iii calls the following method:

15. protected void selectColor() {

a. Color newColor = JColorChooser.showDialog(null, "Choose Color", color);

b. if (newColor != null)c. selectColor(newColor); }

}

This gets called if you press the Custom button. What happens is a new dialog box pops up. In the dialog box you choose a colour, which then calls the method at 5.

The other program in the section extends this one by having a growing palette of colours to choose from. To understand how it works, first add the file ColorRecord.java, and experiment with it and then read the code in the book.

Do the following exercises from Laszlo: 7.12 and 7.13

7.6 Triangulate

A triangulation of a surface is a breaking up of the surface into triangles. There are a multitude of computer applications, both in graphics and in numerical computing, that include a stage of representing the surface by the triangulations. In this section, a triangulation application is developed. The application draws on applications that we have already seen: you can interact with the main panel in much the same way as you could with the point and polygon editing programs, you then have buttons that are on a controls Panel in the South section of a border layout.

34

Page 35: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

In BlueJ , you can import the whole folder of classes you will need for this application by starting a new Project, choosing Import from the Project pull-down menu of the BlueJ window, and then navigating to the Chapter 7 folder, choosing Triangulate and pushing the Import button.

The screen should look like the picture below when you push the import button.

Then run the Triangulate class and experiment with the resulting window. Then read the section of Laszlo carefully, making sure you understand the program.

You should then do the following exercises from Laszlo: 7.14-7.16.

7.7 Final Example: A Drawing package

The Final Example of the Course is a Drawing Package, called DrawPad. We have completed one for you to play with and have left you some uncompleted classes to complete as exercises.

First to see it running: In BlueJ, go to the Project pull-down menu and then choose Open. Navigate to the Chapter 7 Folder and then open DrawPad. A Window should open with the compiled application in it. Run the application, by choosing the main method in the Class called DrawPad. Play with the application a while to get a feeling for everything it does. Then do the following major exercise.

Major Exercise: Start a new project and import the contents of DrawPad Classes from the Chapter 7 folder from your CD. Press the compile button. You will see a lot of errors. These correspond to missing parts of the classes. Read through the chapter so you understand the system fully and fill in all of the missing code.

You will find that this application uses much of what you have learned including composition, inheritance, the Iterator Design Pattern, the Strategy Design Pattern, the Observer Design Pattern: especially to do with Listeners, and graphical constructs in Java. We hope you find this is a fitting culmination to your sessions’s work.

35

Page 36: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

7.8 Summary of the Chapter

Chapter Seven was about frameworks, which are collections of related classes and interfaces that form an application that you can alter to make a new application very rapidly. This is a very powerful form of design reuse. The chapter concentrates on a particular framework: the graphics framework in Java. This framework consists of the AWT (Abstract Windows Toolkit) and Swing. We learned about the event model, which implements the Observer Pattern. We also learned about the Component and Containers of widgets (or graphical user interface objects), which follow the Composite Design Pattern. The Chapter finished with two substantial graphical programming examples that bring together many of the concepts from the whole course.

Examinable things to take from the Chapter:

The notion of Frameworks

The Java Event Model

AWT and Swing

7.9 Summary of the whole Course

This is a course about object orientation. The main thrust of the course was on how object-orientated techniques lead to abstract, well-structured systems that encourage reuse of code and reuse of thought. The main application domain for the course is drawing pictures on screens.

Chapter One provided a high-level introduction to object-orientation in general. We worked through a simple example of a bouncing ball to introduce some object-oriented principles: such as the use of constructors, static versus non-static methods, and the use of inheritance.

Chapter Two taught you to think about, and document, procedures as abstract behaviour. This allows you to work out what procedures you can reuse. This kind of thinking also helps you to design systems easily and effectively. It also helps you to maintain systems by enabling you to replace faulty or superseded methods with minimal and predictable effects. Chapter Two also taught you to decompose problems and to compose procedures that solve parts of the problem. We saw recursion as a special case of that. Sorting was used as a small case study in which the problem was broken down into three sub-problems, the most interesting part of which was the actual sort procedure. We two implementations for that part of the problem: SelectionSort and MergeSort. We saw complexity analyses of each and found that the MergeSort was much more efficient. Because both sorts meet the same specification, we could take out the SelectionSort and slot the MergeSort in its place.

Chapter Three concerned Abstract Data Types and their implementation. The Abstract Data Types carries further the abstractions introduced in Chapter Two. You saw the distinctions among classes, abstract classes and interfaces. We saw examples of two geometric figures specified and implemented: Points and Rectangles. The Rectangle class showed that the implementation might differ from your expectations: while the properties of the RectangleGeometry class were Position, Width, and Length, none of these was stored as a

36

Page 37: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

data field. In this chapter we saw the first use of ApplicationFrames as a way of drawing on a screen. The example, which only drew one rectangle on the screen, was abstracted to form a template that we later used to make more sophisticated drawings.

Chapter Four was about Composition, which is one of the two principal techniques for redeploying classes. The idea is that you have a composite class that has other classes as components. Objects of the composite class own objects of the component classes in the sense that they have total control over them and when the composite dies it takes the components with it. We saw an example of this, which was a class for drawing many rectangles on the screen. The class has components that include a random rectangle class and a random colour class. Rectangles (in terms of their positions and size) and fill colours are chosen randomly. We also saw a PolyLine (like a graph or an open polygon) as a class composed of several Points. There was also a discussion of invariants that are satisfied by the representations of certain classes: the two examples given in the chapter are rationals that are represented by fractions in lowest terms, and ellipses. The chapter finished with another increment in the move towards graphical programming: pictures with which you can interact. A simple game was developed as a first example, and this game was then abstracted to form a template for this kind of application. The template is an instance of composition because it consists of an ApplicationFrame that has a controller as a component.

Chapter Five was about inheritance, which is the second principal technique for redeploying classes. We saw that the three main reasons for using inheritance: inheritance for extension, inheritance for specialisation, and inheritance for abstraction. We saw two or three applications for each of these, including one graphical application. In inheritance for extension the child class adds new behaviour to the behaviour of the parent class: we saw transformable points as an instance of that. Transformable Points have all the behaviour and attributes of Points plus the added ability to be scaled and rotated. These abilities enable them to be used in Affine transformations later in the course. In inheritance for specialization, the child class does something differently from its parent. We saw polygons as an instance of that: polygons inherit from PolyLines, but respond differently to some methods. In inheritance for abstraction we have some parent classes that are not completely implemented but get to the heart of the abstract similarities of several classes. We saw Rectangular Geometries as an abstraction of RectangleGeometries and AbstractGeometries as an abstraction of that. We then saw one of the great benefits of an abstraction hierarchy: polymorphism. Two classes that have an abstract parent in common, or that both implement the same interface, can be joined in the same collection classes; they can also respond to some of the same messages, and can be arguments to the same methods. In Chapter Five we saw an interesting case of this in which a Comparable interface was defined. Any class with a notion of less than or equal to can be declared to implement the Comparable interface. In the chapter, a sorting procedure was developed that works on any class that implements the interface. In this way we can write just one sorting methods and use it to sort arrays of ints, Strings, Rationals,… The chapter finished with a discussion of figures and painters. A figure is a shape plus a painter. The shape knows the outline of the figure, and the painter knows how to paint it on the screen. The chapter presented an inheritance hierarchy for painters. Painter, for example, has two sub classes: DrawPainter and FillPainter. The former strokes the boundary of the shape; the latter fills in the interior.

Chapter Six concerned Design Patterns. Design Patterns are ways of encapsulating useful ideas behind program design. Design Patterns provide a language for talking about high-level designs as well as a way of reusing high-level thinking. In this Chapter we saw three patterns treated extensively with applications to graphics. The three patterns are: the iterator Pattern, the Template Pattern, and the Composite Pattern,. The first of these involves going through the same process repeatedly with different inputs. We saw how this is implemented in Java as an interface. Objects of any class that implements the interface (and all you need is a notion

37

Page 38: 212a subject guide - doc.gold.ac.ukmas01rmz/cis219/Teaching2005/4…  · Web viewThe word “abstract” comes from the Latin abstrahere, ... These work like file systems in Linux

of next thing a way of checking if you are at the end and a notion of removing things) can be treated systematically iteratively. We saw of this in a class called DynamicPolygonIterator that implements Iterator and is used to manipulate DynamicPolygons. The Template Pattern allows you to defer some part of a process that gets filled in differently by different instances. We think of the not quite finished implementation as a template that is ready to have the specific instance slotted into it. The chapter gives an example in terms of Boolean geometries. In that example it is the Boolean operation that slots into the template. The third pattern—the composite pattern—is used to make hierarchies of containment. These work like file systems in Linux or Folders in Windows: A Folder is at the top of the Tree (this is your home directory for example, or your C drive) and every Folder contains Folders and Files. Files are at the bottom and do not contain Folders or Files. In this chapter, we saw how to use this idea to represent pictures that are composed of other pictures. In this chapter, some other patterns are briefly introduced, including the Observer Pattern, which involves objects watching other objects. When the observed object changes in any way, all of the observers are informed and some of them will change accordingly. We saw later, in Chapter Seven, that the Java event model is an instance of this pattern. In that case, the observers are called listeners, and they listen for GUI events, such as mouse clicks.

Chapter Seven was about frameworks, which are collections of related classes and interfaces that form an application that you can alter to quickly make a new application. This is a very powerful form of design reuse. The chapter concentrates on a particular framework: the graphics framework in Java. This framework consists of the AWT (Abstract Windows Toolkit) and Swing. We learned about the event model, which implements the Observer Pattern. We also learned about the Component and Containers of widgets (or graphical user interface objects), which follow the Composite Design Pattern. The Chapter finished with two substantial graphical programming examples that bring together many of the concepts from the whole course.

38