/
05 - Abstract Classes and Interfaces - Exercise

05 - Abstract Classes and Interfaces - Exercise

Overview

The main objective of this exercise is to develop a class hierarchy based on an abstract superclass.

Task 1 - Working with Abstract Class

  1. Create a new IntelliJ Java project.

  2. Download and paste the above files into your new project.

  3. Examine MyShape file which contains the skeleton code for the abstract MyShape class. Note, it defines two protected instance variables - width and height. What is the reason for these variables to be protected?

  4. Define an abstract method called calculateArea(). It does not need any parameters but it will return the calculated area of a shape. As you will discover later, all concrete subclasses of MyShape will need to implement this method.

  5. Examine the class MyRectangle. It is a subclass of MyShape. Define a constructor that takes two arguments - width and height. Pass them directly into the constructor of the superclass.

  6. Implement the calculateArea() method for MyRectangle. (hint: width*height)

  7. Examine the class MyCircle. Define a constructor that takes one argument - radius. Pass this value twice into the constructor of the superclass.

  8. Implement the calculateArea() method. Use Math.PI constant - the are of a circle is defined as PI*r*r where r denotes the radius.

  9. For each concrete class (MyCircle and MyRectangle) override the toString() method so that we can print out information about the shape - what type of shape it is and its area.

  10. Open ShapeTest file. Notice that it contains code to create an array of 4 MyShape-type objects - two circles and two rectangles. In the main method, add a for loop to call the calculateArea() method of each shape in the array.

Task 2 - Create an Interface

Recognise you have two problems now; consider we want to create a class called MyTriangle that will have to have a public double calculateArea() method if it wishes to extend MyShape, what if it does not wish to offer calculateArea functionality but still be a MyShapefor other purposes? Also, if you were to now write a MyTown class with a lovely public double calculateArea() method you will not be able to put it in an array of type MyShape[] as MyTown will extend a different class and cannot be upcast to MyShape. Solution, introduce a Computable interface that MyRectangle, MyCircle and MyTown can choose to implement but which MyTriangle may choose not to implement.

Related content