Advertisement
fosterbl

Shape.java

Feb 19th, 2020
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. public class Shape{
  2.    private String name;
  3.    
  4.    public Shape(String n){
  5.       name = n;
  6.    }
  7.    
  8.    public String getName(){
  9.       return name;
  10.    }
  11.    
  12.    public double area(){
  13.       return 0.0;
  14.    }
  15.    
  16.    public double perimeter(){
  17.       return 0.0;
  18.    }
  19.    
  20.    public String toString(){
  21.       return "Shape";
  22.    }
  23. }
  24.  
  25. class Polygon extends Shape{
  26.    private int numSides;
  27.    
  28.    public Polygon(String n, int ns){
  29.       super(n);
  30.       numSides = ns;
  31.    }
  32.    
  33.    public String toString(){
  34.       return "Polygon with " + numSides + " sides";  
  35.    }
  36. }
  37.  
  38. class Triangle extends Polygon{
  39.    private double leg1, leg2;
  40.    
  41.    public Triangle(double l1, double l2){
  42.       super("Triangle", 3);
  43.       leg1 = l1;
  44.       leg2 = l2;
  45.    }
  46.    
  47.    public double hypotenuse(){
  48.       return Math.sqrt( Math.pow(leg1, 2) + Math.pow(leg2, 2) );
  49.    }
  50.    
  51.    public double perimeter(){
  52.       return leg1 + leg2 + hypotenuse();
  53.    }
  54.    
  55.    public double area(){
  56.       double s = perimeter() / 2;
  57.       return Math.sqrt( s * (s - leg1) * (s - leg2) * (s - hypotenuse()) );
  58.    }
  59.    
  60.    public String toString(){
  61.       return super.toString() + "\n" + getName() + " with legs of length " + leg1 + " and " + leg2;
  62.    }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement