Give an example of polymorphism and what will be inherited between classes. Polymorphism literally means many forms. In an object oriented programming language, we can make methods take different forms through dynamic or late binding. For example, we may want to represent geometric shapes in our program, such as circles, rectangles, and triangles. We could simply code these classes independently. However, we might find there are some commonalities between each of the shapes and what information we want to encode about them. For example, it may be important to find the area of each of these shapes. We can declare all these common functions into an abstract class named Shape.
Shape would declare but not define the method int calculateArea(). We would create subclasses–Circle, Rectangle, and Triangle–that extend Shape. When these subclasses extend Shape, we are making a promise that we will define calculateArea in each of these classes. However, how we calculate the area for each of these geometric shapes is going to differ based on the individual formulae for each geometric shape. Although we have the same method defined in each of our three subclasses, they take different forms. This is the notion of polymorphism.
After the learning this week, can you identify the difference between Abstract classes and Interfaces? Be specific.
Abstract classes | Abstract classes AND Interfaces | Interfaces |
CAN contain instance variables | CANNOT instantiate an object | CANNOT contain instance variables |
Subclasses can extend ONE class (can be abstract) | Subclasses can implement more than one interface | |
Can provide implementations for some of its methods in addition to declaring abstract methods. | Declares abstract methods to be defined in subclasses | Interfaces don’t provide implementations for its methods (*as of Java 8, interfaces can define default methods) |
Update your learning journal from what you experienced this week with class. I enjoyed this week’s project in creating an implementation of a barcode scanner. There was a lot of information to digest in the specifications and, after doing the UML (see below), I found it particularly helpful to draw out the various pieces and how they interact, especially when it came to implementing the DataMatrix class.
Below, you can find illustrations of my approach to most of the DataMatrix class implementation: