CST 338 – Week 4 Learning Journal

Polymorphism

An example of polymorphism that I often see is the “Shapes” class. I used this example in an introductory Java course previously. A class Shapes is defined as:

public abstract class Shapes {
protected double xPos, yPos, zPos, scale;

public Shapes() {

    xPos = 0.0;
    yPos = 0.0;
    zPos = 0.0;
    scale = 0.0;
}
// ...

This creates a class with all the common factors of a geometrical shapes. Then, in child classes Box and Sphere, all of the methods and data specific for that shape are given:

public class Box extends Shapes {
	private double height, width, depth, volume;
	
	public Box() {
		//This is the default constructor for Box
		super();
		height = 0.0;
		width = 0.0;
		depth = 0.0;
		calculateVolume(); 
	}
        //...
	
public class Sphere extends Shapes {
	double radius, volume;
	
	public Sphere() {
		super();
		radius = 0.0;
		calculateVolume();
	}
        //...
	

This allows use to use Shapes methods and data (such as methods that modify their position on the Cartesian plane) on the Sphere and Box objects without having to define them in each class.

Abstract Classes vs. Interfaces

When I was learning Java in my community college courses and I was first introduced to interfaces, my first thought was “Oh, this is just abstract classes from C++”. It wasn’t until later that I actually realized that this is not actually the case, but that Java actually supports abstract classes AND interfaces.

Both abstract classes and interfaces cannot be instantiated and contain abstract methods. However, interfaces only contain undefined classes that do not contain any substance. Abstract classes, however, can contain data and some methods, as seen in the Shapes method above. The way that makes most sense to me is to say that interfaces are more strictly abstract in nature.

Leave a Comment