本文实例讲述了java用接口、多态、继承、类计算三角形和矩形周长及面积的方法。分享给大家供大家参考。具体如下:
定义接口规范:
/**
* @author vvv
* @date 2013-8-10 上午08:56:48
*/
package com.duotai;
/**
*
*
*/
public interface Shape {
public double area();
public double longer();
}
/**
* @author vvv
* @date 2013-8-10 上午09:10:06
*/
package com.duotai;
/**
*
*
*/
public class Triangle implements Shape {
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;
}
/*
* (non-Javadoc)
*
* @see com.duotai.Shape#area()
*/
@Override
public double area() {
double p = (s1 + s2 + s3) / 2;
return Math.sqrt(p * (p - s1) * (p - s2) * (p - s3));
}
/*
* (non-Javadoc)
*
* @see com.duotai.Shape#longer()
*/
@Override
public double longer() {
return s1 + s2 + s3;
}
}
/**
* @author vvv
* @date 2013-8-10 上午09:12:06
*/
package com.duotai;
/**
*
*
*/
public class Director implements Shape {
double s1;
double s2;
// 初始化一个长方形,并赋予该长方形两边长
public Director(double s1, double s2) {
this.s1 = s1;
this.s2 = s2;
}
/*
* (non-Javadoc)
*
* @see com.duotai.Shape#area()
*/
@Override
public double area() {
// TODO Auto-generated method stub
return s1 * s2;
}
/*
* (non-Javadoc)
*
* @see com.duotai.Shape#longer()
*/
@Override
public double longer() {
// TODO Auto-generated method stub
return 2 * (s1 + s2);
}
}
/**
* @author vvv
* @date 2013-8-10 上午09:13:30
*/
package com.duotai;
/**
*
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Shape triangle = new Triangle(3, 4, 8);
// 新建一个三边长为3,4,5的三角形
Shape tri = new Triangle(3, 4, 5);
Shape 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());
}
}
希望本文所述对大家的java程序设计有所帮助。