Define two derived classes of the abstract class ShapeBase in Listing 8.19. Your
ID: 3658970 • Letter: D
Question
Define two derived classes of the abstract class ShapeBase in Listing 8.19. Your two classes will be called RightArrow and LeftArrow. These classes will be like the classes Rectangle and Triangle, but they will draw arrows that point right and left, respectively. For example, the following arrow points to the right: The size of the arrow is determined by two numbers, one for the length of the "tail" and one for the width of the arrowhead. (The width is the length of the vertical base.) The arrow shown here has a length of 16 and a width of 7. The width of the arrowhead cannot be an even number, so your constructors and mutator methods should check to make sure that it is always odd. Write a test program for each class that tests all the methods in the class. You can assume that the width of the base of the arrowhead is at least 3.Explanation / Answer
Thats how the framework will be
public interface ShapeInterface{
public void setOffset(int offset);
public int getOffset();
public void drawAt(int lineNumber);
public void drawHere();
}
--------------------------------------------------------------------------------------------------------------------------
// Base class (ShapeBase)
public abstract class ShapeBase implements ShapeInterface{
protected int offset; // I made offset protected so that the subclasses can refrence it directly
public void setOffset(int newOffset) { offset = newOffset; }
public int getOffset() { return offset; }
public abstract void drawHere();
public void drawAt(int lineNumber) { for(int i=0; i<lineNumber; i++) System.out.println();
drawHere();
}
}
--------------------------------------------------------------------------------------------------------------------------
// Sample Driver for Test #1
public class arrowDriver{
public static void main (String[] args){ ShapeBase[] arrows = new ShapeBase[6];
//constructors take (int length, int width)
arrows[0] = new RightArrow (11,5);
arrows[1] = new LeftArrow (11,5);
arrows[2] = new RightArrow (8,3);
arrows[3] = new LeftArrow (8,3);
arrows[4] = new RightArrow (16,11);
arrows[5] = new LeftArrow (16,12); // constructor adjusts the width to odd number 11
arrows[0].setOffset(9);
arrows[1].setOffset(9);
arrows[2].setOffset(6);
arrows[3].setOffset(6);
arrows[4].setOffset(0);
arrows[5].setOffset(0);
for(ShapeBase arrow : arrows) System.out.println(arrow); // Both Right and Left Arrow have toString methods
LeftArrow arrow1 = new LeftArrow(16,22); //constructor adjusts the width to odd number 21
arrow1.setOffset(3);
RightArrow arrow2 = new RightArrow(16,22); //constructor adjusts the width to odd number 21
arrow2.setOffset(3);
arrow1.drawAt(5);
arrow2.drawAt(5);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.