With object-oriented programming classes and objects can be


Objects vs. Type Case

With object-oriented programming, classes and objects can be used to avoid "type- case" statements. Here is a program in which a form of case statement is used that inspects a user-de?ned type tag to distinguish between different classes of shape objects. This program would not statically type check in most typed languages because the correspondence between the tag ?eld of an object and the class of the object is not statically guaranteed and visible to the type checker. However, in an untyped language such as Smalltalk, a program like this could behave in a computationally reasonable way:

enum shape tag {s point, s circle, s rectangle }; class point {
shape tag tag;
int x; int y;
point (int xval, int yval)
{ x = xval; y = yval; tag = s point; }
int x coord () { return x; }
int y coord () { return y; }
void move (int dx, int dy) { x += dy; y += dy; }
};
class circle { shape tag tag; point c;
int r;
circle (point center, int radius)
{ c = center; r = radius; tag = s circle }
point center () { return c; }
int radius () { return radius; }
void move (int dx, int dy) { c.move (dx, dy); }
void stretch (int dr) { r += dr; }
};
class rectangle { shape tag tag; point tl;
point br;
rectangle (point topleft, point botright)
{ tl = topleft; br = botright; tag = s rectangle; }
point top left () { return tl; }
point bot right () { return br; }
void move (int dx, int dy) { tl.move (dx, dy); br.move (dx, dy); }
void stretch (int dx, int dy) { br.move (dx, dy); }

};
/* Rotate shape 90 degrees. */ void rotate (void *shape) {
switch ((shape tag *) shape) {
case s point: case s circle:
break;
case s rectangle:
{
rectangle *rect = (rectangle *) shape; int d = ((rect->bot right ().x coord ()
- rect->top left ().x coord ()) - (rect->top left ().y coord ()
- rect->bot right ().y coord ())); rect->move (d, d);
rect->stretch (-2.0 * d, -2.0 * d);
}
}
}

(a) Rewrite this so that, instead of rotate being a function, each class has a rotate method and the classes do not have a tag.

(b) Discuss, from the point of view of someone maintaining and modifying code, the differences between adding a triangle class to the ?rst version (as previously written) and adding a triangle class to the second [produced in part (a) of this question].

(c) Discuss the differences between changing the de?nition of rotate (say, from 90? to the left to 90? to the right) in the ?rst and the second versions. Assume you have added a triangle class so that there is more than one class with a nontrivial rotate method.

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: With object-oriented programming classes and objects can be
Reference No:- TGS01269953

Expected delivery within 24 Hours