Description
1. How will the Duck class use the FlyBehavior and QuackBehavior interfaces? Implement the diagram in Java, and make sure the answer to this question is clear in your code. To implement the methods like fly() and quack(), just print a phrase to the console, like “Flying with wings” or “Quack by squeaking.”
To test your code, create a Main class like the following:
Output should look like this:
2. Create Java classes for Triangle, Rectangle, and Circle. Provide each class with a method
public double computeArea()
Make all of these classes immutable. (Follow the guidelines in the slides for creating this type of class – included with this lab.) Provide one constructor for each class; the constructor should accept the data necessary to specify the figure, and to compute its area. The values accepted by the constructor should be stored in (private) instance fields of the class. For example, Rectangle should have instance fields width and length, and the constructor should look like this
public Rectangle(double width, double length)
Whenever you create instance fields for one of these classes, provide public accessors for them (but do not provide mutators since the class is supposed to be immutable – for instance, the dimensions of a Rectangle should be read-only). For example, you will have in the Rectangle class:
private double width; public double getWidth() { return width;
}
Create a fourth class Main that will, in its main method, create multiple instances of these figures
compute and write to the console the sum of the areas. In order to do this, you will need to create an appropriate interface that will be implemented by each of these geometric figures.
Typical output:
Sum of Areas = 37.38
Draw a class diagram that includes all the types mentioned in this problem.
Here are some area formulas:
Area of a rectangle = width * height
Area of a triangle = 1/2 * base * height
Area of a circle = PI * radius * radius
3. In Lesson 2, one way of maintaining a unidirectional one-many relationship was mentioned – in that approach, creation of secondary objects (in the example, these were of type Order) was controlled by limiting visibility of the constructor to package level. For this problem, modify the code mentioned there (which can be found in the code folder for Lab 5) so that construction of Order objects is controlled by a factory method. The guidelines given in Lesson 2 for maintaining a onemany unidirectional association are reproduced here:
Note: An example of using a factory method to maintain an association relationship was given in the Lesson 5 slides (see lesson5.lecture.factorymethods6 for the code showing a factory method, and see lesson2.lecture.unidirectional.onemany to see another way to code a one-many unidirectional relationship).




Reviews
There are no reviews yet.