Google Answers Logo
View Question
Q: Java Program ( Answered,   0 Comments )
Subject: Java Program
Category: Computers > Programming
Asked by: math01-ga
List Price: $20.00
Posted: 28 Jan 2003 05:17 PST
Expires: 27 Feb 2003 05:17 PST
Question ID: 149471
Write a program that uses a class hierarchy and implement it using
inheritance. You will use the problem of computing properties of
geometric shapes. However, restrict the program to two different types
of triangles. Use the hierarchy shown here.

Shape -> triangle
Triangle -> Right and Equilateral

Implement an appropriate set of constructors for each class. Represent
each triangle by the coordinates of the vertices. Write methods to
compute the perimeter and the length of the longest and the shortest
side. Override any method in the sub classes if they can be computed
more efficiently than the general formula for any arbitrary triangles.
For example, you can compute the perimeter of an equilateral triangle
easily by tripling the length of any side.

Add the appropriate code so that the program will: 

Design a class hierarchy of shapes, as defined above 
Implement the classes using inheritance 
Write a new class to test the shape objects

Define a class called Points, which stores the x and y coordinates of
a point. It should also have methods called x and y to extract the x
and y coordinates.
Use an abstract class to implement shape class; clearly identify
abstract methods.
Use inheritance to define the other classes. 
Implement the methods for each class. 
Add a user class to test the functionality of your classes.
Subject: Re: Java Program
Answered By: theta-ga on 28 Jan 2003 12:00 PST
Hi math01-ga,
   I have provided the required Java code below. To compile and run
this code, you will need the Java2 SDK. You can download the Java SDK
from :
        - Download : Java(TM) 2 SDK, Standard Edition, v 1_4_0_03
          ( )

   A free Java IDE (if you need one) can be found at :
        - The RealJ Java IDE
          ( )

   The code provided below has been tested with RealJ and JDK 1.4

Copy this code into a file called, and then compile it.
The code contains the following classes :
 - Point : This class stores the x,y coordinates of a point
 - Shape : Abstract class from which the other classes inherit
 - Triangle : contains methods to calculate Perimeter and the
shortest/longest side of a triangle.
 - RightTriangle : Inherits from Triangle, specific to Right triangles
 - EquilateralTriangle : Inherits from Triangle, overrides its methods
to optimize them for an equilateral triangle
 - TestShape : contains the main function. Creates an instance of the
Triangle, RightTriangle and EquilateralTriangle classes and prints out
the output from their methods.

*********** Code from *************

import java.lang.Math;

// Utility Class Point
// Stores x,y coordinates of a point
class Point
   private int x,y;
   // Constructor
   public Point( int newX, int newY ) 
      // initialize x and y
      x = newX;
      y = newY;
   // Returns value of the X coordinate
   public int X()
     return x;

   // Returns value of the Y coordinate
   public int Y()
     return y;

   // Utility Function
   // Calculates the linear distance between 
   // this point and the given point pt.
   // Used in Triangle to calculate length of sides
   public double DistanceBetween(Point pt)
     double distance,xd,yd;
     xd = x - pt.X();
     yd = y - pt.Y();
     distance = Math.sqrt( xd*xd + yd*yd );

     return distance;

}  // End of Point class


// Shape Class
// Abstract class from which other shapes inherit

abstract class Shape
 // All shapes have a perimeter, so define abstract method
 // returns a double that is the perimeter of the shape
   abstract double Perimeter();   


// Triangle class, inherits from abstract Shape class
// Has child classes : RightTriangle and EquilateralTriangle

class Triangle extends Shape
   protected Point vertexA, vertexB, vertexC;
   // Length of the 3 sides
   protected double sideAB, sideBC, sideAC;
	public Triangle()
	  sideAB = sideBC = sideAC = 0;
   // Constructor : Takes 3 vertices, calculates sides
   public Triangle (Point newA, Point newB, Point newC)
      vertexA = newA;
      vertexB = newB;
      vertexC = newC;

      sideAB = vertexA.DistanceBetween(vertexB);
      sideBC = vertexB.DistanceBetween(vertexC);
      sideAC = vertexA.DistanceBetween(vertexC);
    // calculates and returns perimeter of this triangle
    public double Perimeter()
      return (sideAB + sideBC + sideAC);

    // calculates and returns the length of
    // the longest side of this triangle 
    public double LongestSide()
      return (sideAB > sideBC ? ( sideAB > sideAC ? sideAB : sideAC) :
(sideBC>sideAC ?  sideBC : sideAC) );

    //calculates and returns the length of 
    //the shortest side of this triangle 
    public double ShortestSide()

      if ( sideAB < sideBC )
         if( sideAB < sideAC)
            return sideAB;
            return sideAC;
         if( sideBC < sideAC )
            return sideBC;
            return sideAC;

    // OverRide toString() to display the vertices of the triangle
    public String toString()
        return " Triangle Vertices : "
               + "A(" + vertexA.X() + "," + vertexA.Y() + "), "
               + "B(" + vertexB.X() + "," + vertexB.Y() + "), "
               + "C(" + vertexC.X() + "," + vertexC.Y() + ").";

} // End of Triangle class


class RightTriangle extends Triangle
    // Constructor
    public RightTriangle(Point newA, Point newB, Point newC)
      // assume triangle is  A |\
      //                       | \
      //                     B |__\ C
      // thats is : AB = perpendicular
      //            BC = base
      //            AC = hypotenuse
      // We just call the Triangle class constructor
      super ( newA, newB, newC );
    // The Perimeter will be calculated the same as superclass
    // So we will not override the Perimeter method of the Triangle

    // In a right triangle, the longest side will always be the
    public double LongestSide()
      // return hypotenuse
      return sideAC;

    // In a right triangle, hypotenuse >= other two sides
    // So we just compare base and the perpendicular
    // and return the shortest one
    public double ShortestSide()
      return ( sideAB < sideBC ? sideAB : sideBC );

} // End of the RightTriangle class


class EquilateralTriangle extends Triangle
    public EquilateralTriangle(Point newA, Point newB, Point newC )
      vertexA = newA;
      vertexB = newB;
      vertexC = newC;
      // Need to calculate only one side
      // since all sides have same length 
      sideAB = vertexA.DistanceBetween(vertexB);
      sideBC = sideAB; 
      sideAC = sideAB;

    // Perimeter = 3 * length of any side
    public double Perimeter()
      return 3 * sideAB;

    // Longest side = any side ( since all sides have same length)
    public double LongestSide()
      return sideAB;

    // Shortest side = any side ( since all sides have same length)
    public double ShortestSide()
      return sideAB;

} // End Of EquilateralTriangle class


public class TestShape
  public static void main (String [] args)
    Point A = new Point(1,4);
    Point B = new Point(2,0);
    Point C = new Point(5,2);
    Triangle tri = new Triangle(A,B,C);

    System.out.print("Created New Triangle Object.\n" + tri);
    System.out.println("\n Perimeter = " + tri.Perimeter() );
    System.out.println(" Longest Side = " + tri.LongestSide() );
    System.out.println(" Shortest Side = " + tri.ShortestSide() );

    // Test RightTriangle class
    A = new Point(1,4);
    B = new Point(0,0);
    C = new Point(7,0);
    RightTriangle rtTri = new RightTriangle(A,B,C);

    System.out.print("Created New RightTriangle Object.\n" + rtTri);
    System.out.println("\n Perimeter = " + rtTri.Perimeter() );
    System.out.println(" Longest Side = " + rtTri.LongestSide() );
    System.out.println(" Shortest Side = " + rtTri.ShortestSide() );
    // Test EquilateralTriangle class
    A = new Point(0,1);
    B = new Point(0,0);
    C = new Point(1,0);
    EquilateralTriangle eqTri = new EquilateralTriangle(A,B,C);

    System.out.print("Created New EquilateralTriangle Object.\n" +
    System.out.println("\n Perimeter = " + eqTri.Perimeter() );
    System.out.println(" Longest Side = " + eqTri.LongestSide() );
    System.out.println(" Shortest Side = " + eqTri.ShortestSide() );

*********** End of ****************

  Please note that in the constructor of the RightTriangle class, I
have made the assumption that the side AC is the Hypotenuse. This
assumption was necessary because I needed the hypotenuse values in
order to optimize the LongestSide() and the ShortestSide() methods.
Without this assumption, the RightTriangle class would have been
exactly the same as the Triangle class.

  If there are any aspects of the above program that you want
modified, then please do not hesitate to ask me. I will be glad to
modify it to suit your needs. Please note that the code, as it stands
right now, completely satisfies your question.
  Please do not rate this answer until it has been answered to your
satisfaction. I will be glad to make any changes you want to the
program, until you are satisfied.
  If you need any clarifications, just ask!


Google Search Terms Used :
    download Java SDK
    java default access private public
    java override tostring

Clarification of Answer by theta-ga on 28 Jan 2003 12:27 PST
  Please note that due to the way the Google Answers website works,
long lines of text get pushed onto the next line. This is what has
happened to two comments in the above Java code. This is why, if you
directly copy and paste the above code, it will give an error while
compiling. The error can be easily fixed. In the RightTriangle class
change the following lines :
    // The Perimeter will be calculated the same as superclass
    // So we will not override the Perimeter method of the Triangle
    // In a right triangle, the longest side will always be the

to these lines :
    // The Perimeter will be calculated the same 
    // as superclass Triangle
    // So we will not override the Perimeter method
    // of the Triangle class
    // In a right triangle, the longest side 
    // will always be the hypotenuse

 Thats it! The code will compile now. If you have any other problems,
I will be glad to help you out.

Request for Answer Clarification by math01-ga on 29 Jan 2003 05:58 PST
Hi theta-ga,

I have not compiled the program yet. However, do I have to compile
every class before running the program?

Clarification of Answer by theta-ga on 29 Jan 2003 06:35 PST
Hi math01-ga,
   To keep compilation simple, all of the code provided above is
contained in a single file. Here are the steps you need to take to
compile the above program:
    - Create an empty file
    - Copy the Java code provided and paste it into
    - Make the changes to the code, as noted in my earlier
    - Save the file
    - To compile the file, use the following command:
      This assumes that your javac.exe and are both in
your search path. If you get a file not found error, provide the full
path to the files.
    - After compilation, a separate class file will be created for
each of the classes in
    - To run the program, give the command :
           java TestShape
      Please note that TestShape is not followed by any file

If you so want, you can move each class to its own separate file. In
this case, when you compile the file containing the TestShape class,
the compiler will detect that it needs to compile the other classes
and will do so automatically. Just make sure that you name the Java
file with the class name.(For eg:,, etc). The remaining instructions will remain the same.
If you have any problems, contact me. :-)

Hope this helps. 
For more instructions, check out :
        - How to compile a Java program
        - Notes on Java 
          ( )

If you need any clarifications, just ask!

Request for Answer Clarification by math01-ga on 30 Jan 2003 10:26 PST
Hi theta-ga,
I was just wondering since we are talking about inheritance. Lets
suppose that we have a parent object with PRIVATE members, Can they be
inherited to its children?

Clarification of Answer by theta-ga on 30 Jan 2003 10:57 PST
Hi math01-ga,
   The answer to your question is no. The private access specifier
specifies that the method/variable following it, can be accessed from
within that class ONLY, and not by classes that inherit from it or are
in the same package.
   For more information, check out the access specifier chart
available at :
        - The Java Tutorial : Controlling Access to Members of a Class


Request for Answer Clarification by math01-ga on 10 Feb 2003 03:28 PST
Hi theta-ga,
I was just wondering if you can help me out with this program. I have
tried  to compiled and run this gui program but nothing happened (no
activity on screen just the dos box). Below is the program.


import java.awt.*;
import javax.swing.*;

public class NewGUI extends JApplet {
    // set up row 1
    JPanel row1 = new JPanel();
    JLabel ptLabel = new JLabel("Choose: ");
    JComboBox playType = new JComboBox();
    // set up row 2
    JPanel row2 = new JPanel();
    JLabel numbersLabel = new JLabel("Your picks: ", JLabel.RIGHT);
    JTextField[] numbers = new JTextField[6];
    JLabel winnersLabel = new JLabel("Winners: ", JLabel.RIGHT);
    JTextField[] winners = new JTextField[6];
    // set up row 3
    JPanel row3 = new JPanel();
    ButtonGroup option = new ButtonGroup();
    JCheckBox stop = new JCheckBox("Stop", true);
    JCheckBox play = new JCheckBox("Play", false);
    JCheckBox reset = new JCheckBox("Reset", false);
    // set up row 4
    JPanel row4 = new JPanel();
    JLabel got3Label = new JLabel("3 of 6: ", JLabel.RIGHT);
    JTextField got3 = new JTextField();
    JLabel got4Label = new JLabel("4 of 6: ", JLabel.RIGHT);
    JTextField got4 = new JTextField();
    JLabel got5Label = new JLabel("5 of 6: ", JLabel.RIGHT);
    JTextField got5 = new JTextField();
    JLabel got6Label = new JLabel("6 of 6: ", JLabel.RIGHT);
    JTextField got6 = new JTextField(10);
    JLabel drawingsLabel = new JLabel("Drawings: ", JLabel.RIGHT);
    JTextField drawings = new JTextField();
    JLabel yearsLabel = new JLabel("Years: ", JLabel.RIGHT);
    JTextField years = new JTextField();
    public void init() {
        GridLayout appletLayout = new GridLayout(5, 1, 10, 10);
        Container pane = getContentPane();

        FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,
            10, 10);
        playType.addItem("Quick Pick");

        GridLayout layout2 = new GridLayout(2, 7, 10, 10);
        for (int i = 0; i < 6; i++) {
            numbers[i] = new JTextField();
        for (int i = 0; i < 6; i++) {
            winners[i] = new JTextField();

        FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER,
            10, 10);

        GridLayout layout4 = new GridLayout(2, 6, 20, 10);
    public static void main(String[] arguments) {
       NewGUI ng = new NewGUI();

Clarification of Answer by theta-ga on 12 Feb 2003 11:11 PST
Hi math01-ga,
   I see that you have graduated onto more interesting( and
challenging?) aspects of the Java language. Good for you!
   Unfortunately, your new request for clarification goes completely
beyond the scope of the current question, and I'm afraid I cannot
answer it here. I recommend that you post this new request as a
seperate question on Google Answers. This would also give the other
qualified researchers a chance to work on it. If you would rather that
this question be answered only by me, then you can specify your new
question with the text "For theta-ga only".
Hope this helps.
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  

Google Home - Answers FAQ - Terms of Service - Privacy Policy