接口和继承都是多态的一种表现形式,所以一个小程序可以解决所以的问题!
马上写出来
package day0507;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Shap triangle=new Triangle(3, 4, 8);//新建一个三边长为3,4,5的三角形
Shap tri=new Triangle(3, 4, 5);
Shap director=new Director(10, 20);//新建一个两边长为10,20的长方形
System.out.println("三角形triangle的周长为:"+triangle.longer());
System.out.println("三角形triangle的面积为:"+triangle.area());
System.out.println("三角形tri的周长为:"+tri.longer());
System.out.println("三角形tri的面积为:"+tri.area());
System.out.println("该长方形的周长为:"+director.longer());
System.out.println("该长方形的面积为:"+director.area());
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package day0507;
public class Director implements Shap {
double s1;
double s2;
//初始化一个长方形,并赋予该长方形两边长
public Director(double s1,double s2){
this.s1=s1;
this.s2=s2;
}
//计算长方形面积
public double area() {
return s1*s2;
}
//计算长方形周长
public double longer() {
return 2*(s2+s2);
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package day0507;
public class Triangle implements Shap {
double s1;
double s2;
double s3;
//初始化一个三角形对象,并赋予该三角形三边长
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("输入的三边长"+s1+"、"+s2+"、"+s3+"不能组成一个三角形,请重新输入三边长!");
}
}
//判断是否是个三角形
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;
}
//使用海伦公式计算三角形面积
public double area() {
double p=(s1+s2+s3)/2;
return Math.sqrt(p*(p-s1)*(p-s2)*(p-s3));
}
//计算三角形周长
public double longer() {
return s1+s2+s3;
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package day0507;
public interface Shap {
public double area();
public double longer();
}