Lesson 5

Objectives

  • abstract classes
  • interfaces
  • polimorfism

Documentation

Exercises

Exercise 1

Follow the instructions and implement the program according to specification . Create an appropriate test class for testing the program. For testing purpose you will create an array of shapes and then call and display getArea() and getPermiter() for each object in the array.

In this exercise, Shape shall be defined as an abstract class, which contains:

  • Two protected instance variables color(String) and filled(boolean). The protected variables can be accessed by its subclasses and classes in the same package. They are denoted with a '#' sign in the class diagram.
  • Getter and setter for all the instance variables, and toString().
  • Two abstract methods getArea() and getPerimeter() (shown in italics in the class diagram).
  • The subclasses Circle and Rectangle shall override the abstract methods getArea() and getPerimeter() and provide the proper implementation. They also override the toString().

Exercise 2

Follow the instructions and implement the program according to specification . Create an appropriate test class for testing the program.

public interface Image {
   void display();
}
 
public class RealImage implements Image {
 
   private String fileName;
 
   public RealImage(String fileName){
      this.fileName = fileName;
      loadFromDisk(fileName);
   }
 
   @Override
   public void display() {
      System.out.println("Displaying " + fileName);
   }
 
   private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }
}
 
public class ProxyImage implements Image{
 
   private RealImage realImage;
   private String fileName;
 
   public ProxyImage(String fileName){
      this.fileName = fileName;
   }
 
   @Override
   public void display() {
      if(realImage == null){
         realImage = new RealImage(fileName);
      }
      realImage.display();
   }
}

For the image application in the code above:

  • create the UML class diagram;
  • add a new implementation of the Image interface named 'RotatedImage' which will display message “Display rotated ”+fileName;
  • add necessary changes in ProxyImage class so that depending on a constructor argument given in this class the proxy to call either real image display or rotated image display function;

Exercise 3

Implement application based on the UML class diagram bellow. Create a test class for testing the program.

Follow the instructions and implement the program according to specification .

  • implement the application based on the UML class diagram above;
  • control() method will read and display temperature and light values with a period of 1 second for duration of 20 seconds;

Exercise 4

Update the Controller class from exercise 3 to be implemented as a Singleton.