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
Create a new IntelliJ Java project.
Download and paste the above files into your new project.
Examine
MyShape
file which contains the skeleton code for the abstractMyShape
class. Note, it defines two protected instance variables -width
andheight
. What is the reason for these variables to beprotected
?Define an
abstract
method calledcalculateArea()
. It does not need any parameters but it will return the calculated area of a shape. As you will discover later, all concrete subclasses ofMyShape
will need to implement this method.Examine the class
MyRectangle
. It is a subclass ofMyShape
. Define a constructor that takes two arguments -width
andheight
. Pass them directly into the constructor of the superclass.Implement the
calculateArea()
method for MyRectangle. (hint: width*height)Examine the class
MyCircle
. Define a constructor that takes one argument - radius. Pass this value twice into the constructor of the superclass.Implement the
calculateArea()
method. UseMath.PI
constant - the are of a circle is defined as PI*r*r where r denotes the radius.For each concrete class (
MyCircle
andMyRectangle
) override thetoString()
method so that we can print out information about the shape - what type of shape it is and its area.Open
ShapeTest
file. Notice that it contains code to create an array of 4MyShape
-type objects - two circles and two rectangles. In themain
method, add a for loop to call thecalculateArea()
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 MyShape
for 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.