fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5.  
  6. // an interface
  7. interface Shape {
  8. public double calculateArea();
  9. }
  10.  
  11. //Rectangle class
  12.  
  13. class Rectangle implements Shape {
  14.  
  15. // fields/variables
  16.  
  17. double length;
  18.  
  19. double width;
  20.  
  21. //constructor
  22.  
  23. public Rectangle(double length, double width)
  24. {
  25. setLength(length);
  26. setWidth(width);
  27. }
  28.  
  29. //getters and setters
  30.  
  31. public double getLength()
  32. {
  33. return length;
  34. }
  35.  
  36. public void setLength(double length)
  37. {
  38. if(length > 0)
  39. this.length = length;
  40. }
  41.  
  42. public double getWidth()
  43. {
  44. return width;
  45. }
  46.  
  47. public void setWidth(double width)
  48. {
  49. if(width > 0)
  50. this.width = width;
  51. }
  52.  
  53. // returning the area of rectangle
  54.  
  55. public double calculateArea()
  56. {
  57. return length * width;
  58. }
  59.  
  60. }// end of Rectangle class
  61.  
  62. //Circle class
  63.  
  64. class Circle implements Shape
  65.  
  66. {
  67. // fields/variables
  68. double radius;
  69.  
  70. //constructor
  71.  
  72. public Circle(double radius)
  73. {
  74. setRadius(radius);
  75. }
  76.  
  77. //getters and setters
  78.  
  79. public double getRadius()
  80. {
  81. return radius;
  82. }
  83.  
  84. public void setRadius(double radius)
  85. {
  86. if(radius > 0)
  87. this.radius = radius;
  88. else
  89. this.radius = 0.0;
  90. }
  91.  
  92. // returning area of circle
  93.  
  94. public double calculateArea()
  95. {
  96. return Math.PI * radius * radius;
  97. }
  98.  
  99.  
  100. }
  101.  
  102. // to test the objects of Rectangle and Circle
  103.  
  104. class ShapeTest {
  105.  
  106. public static void main(String [] args)
  107. {
  108. Shape [ ] diagrams = new Shape [3];
  109. Shape r=new Rectangle(5,4);
  110. Shape c=new Circle(5);
  111. double r_area;
  112. double c_area;
  113. r_area=r.calculateArea();
  114. c_area=c.calculateArea();
  115.  
  116. System.out.println("area of Rectangle is : "+r_area);
  117. System.out.println("area of Circle is : "+c_area);
  118. }
  119. }
Success #stdin #stdout 0.1s 36140KB
stdin
Standard input is empty
stdout
area of Rectangle is : 20.0
area of Circle is : 78.53981633974483