Java USES interfaces polymorphism inheritance and classes to calculate the perimeter and area of triangles and rectangles
- 2020-04-01 03:49:57
- OfStack
This article illustrates how Java USES interfaces, polymorphism, inheritance, and classes to calculate the perimeter and area of triangles and rectangles. Share with you for your reference. The details are as follows:
Define the interface specification:
package com.duotai;
public interface Shape {
public double area();
public double longer();
}
package com.duotai;
public class Triangle implements Shape {
double s1;
double s2;
double s3;
//Initializes a triangle object and gives the triangle three sides length
public Triangle(double s1, double s2, double s3) {
if (isTri(s1, s2, s3)) {
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
} else {
System.out.println(" Input three side length " + s1 + " , " + s2 + " , " + s3
+ " Cannot form a triangle, please re-enter the three side length! ");
}
}
//It's a triangle
public boolean isTri(double s1, double s2, double s3) {
if (s1 + s2 < s3) {
return false;
}
if (s1 + s3 < s2) {
return false;
}
if (s2 + s3 < s1) {
return false;
}
return true;
}
@Override
public double area() {
double p = (s1 + s2 + s3) / 2;
return Math.sqrt(p * (p - s1) * (p - s2) * (p - s3));
}
@Override
public double longer() {
return s1 + s2 + s3;
}
}
package com.duotai;
public class Director implements Shape {
double s1;
double s2;
//Initializes a rectangle and lengthens both sides of the rectangle
public Director(double s1, double s2) {
this.s1 = s1;
this.s2 = s2;
}
@Override
public double area() {
// TODO Auto-generated method stub
return s1 * s2;
}
@Override
public double longer() {
// TODO Auto-generated method stub
return 2 * (s1 + s2);
}
}
package com.duotai;
public class Test {
public static void main(String[] args) {
Shape triangle = new Triangle(3, 4, 8);
//Create a new triangle with 3,4,5 sides
Shape tri = new Triangle(3, 4, 5);
Shape director = new Director(10, 20);
//Create a new rectangle with 10,20 on each side
System.out.println(" triangle triangle The perimeter is: " + triangle.longer());
System.out.println(" triangle triangle Is: " + triangle.area());
System.out.println(" triangle tri The perimeter is: " + tri.longer());
System.out.println(" triangle tri Is: " + tri.area());
System.out.println(" The perimeter of the rectangle is: " + director.longer());
System.out.println(" The area of the rectangle is: " + director.area());
}
}
I hope this article has been helpful to your Java programming.