Java Reference
In-Depth Information
Figure 6.7
The output of the ParentDemo program.
Lab 6.1: Implementing Inheritance
The purpose of this lab is to become familiar with implementing inheri-
tance in Java. You will write a class named Polygon that is subclassed by
a Triangle class.
1. Write a class called Polygon that has two fields: an int for the num-
ber of sides and a double for the area. Add a method called get-
NumberOfSides() that prints out and returns the number of sides.
2. Override the toString() method in Polygon to return a nice string
representation of your Polygon class.
3. Add a constructor to Polygon that takes in an int to represent
the number of sides and prints out the message “Inside Polygon
constructor.”
4. Save and compile the Polygon class.
5. Write a class called Triangle that extends Polygon. Add two int
fields: one for the base and one for the height. (Triangles have a base
and a height.)
6. Add a constructor to Triangle that takes in two int's for the base and
height. The constructor needs to use super() to invoke the construc-
tor in Polygon, passing in 3 for the number of sides. Print out the
message “Inside Triangle constructor.”
7. Add a toString() method to Triangle that prints out the triangle's
base and height.
8. Add a getArea() method to Triangle that computes and returns the
area. The formula for the area of a triangle is:
area = 1/2 (base * height)
Search WWH ::




Custom Search