Lesson 4

Abstract classes, interfaces and polimorfism.

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.

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

Create the UML class diagram for the program bellow. Add a new type of bird, and modify BirdController in order to handle the new type of bird.

class Bird {
            public void move(){
                        System.out.println("The bird is moving.");
            }
}
 
class Penguin extends Bird{
            public void move(){
                        System.out.println("The PENGUIN is swiming.");
            }
}
 
class Goose extends Bird{
            public void move(){
                        System.out.println("The GOOSE is flying.");
            }
}
 
public class BirdController{
            Bird[] birds = new Bird[3];
            BirdController(){
                        birds[0] = createBird();
                        birds[1] = createBird();
                        birds[2] = createBird();
            }
            public void relocateBirds(){
                        for(int i=0;i<birds.length;i++)
                                    birds[i].move();
            }
 
            private Bird createBird(){
                        int i = (int)(Math.random()*10);
                        if(i<5)
                                    return new Penguin();
                        else
                                    return new Goose();
            }
 
            public static void main(String [] args){
                        BirdController bc = new BirdController();
                        bc.relocateBirds();
            }          
}

Exercise 3

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

Exercise 4

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