Inheritance and Polymorphism

 

 

 

Problem #1:

The programs below implement the Shape-Circle-Cylinder Hierarchy shown in the following link:

 

Class Diagram for Shape-Circle-Cylinder

 

Following is a short summary of all the programs that are needed to implement the above hierarchy. The programs below and the concepts of abstract classes, abstract methods, inheritance and polymorphism will be discussed in detail in class.

 

The Shape Class: Shape.java

·        Shape.java is called an abstract class. It is purely generic in its definition and is only used by other classes for inheritance.

·        Can contain abstract methods, which contain no implementation (are empty), but must be implemented in the classes that inherit from the Shape class.

 

The Circle Class: Circle.java

·        Inherits from the Shape class. The Circle class is called a concrete class (all methods are fully implemented).

·        Has access to the public methods and private variables of the Shape class (see program code for the proper syntax).

·        Must provide implementation (override) for the abstract methods defined in the Shape class.

 

The Cylinder Class: Cylinder.java

·        Inherits from the Circle class. The Cylinder class is also a concrete class (all methods are fully implemented).

·        Has access to the public methods and private variables of the Circle class (see program code for the proper syntax).

·        Must provide implementation (override) for the abstract methods defined in the Shape class.

 

ShapeCircleCylinderTest.java:

·        Creates an array of type Shape

·        Objects of type Circle and Cylinder are created and subsequently stored in the array of type Shape.

·        A loop runs through the array of type Shape and prints the properties of Circle and Cylinder (see program code and program output).

 

 

 

Program Output:

 

Circle :

Center = (5 , 5)

Radius = 2

Area = 12.566

Volume = 0.000

 

Cylinder :

Center = (2 , 2)

Radius = 1

Height = 5

Area = 37.699

Volume = 15.708