java用接口、多態、繼續、類盤算三角形和矩形周長及面積的辦法。本站提示廣大學習愛好者:(java用接口、多態、繼續、類盤算三角形和矩形周長及面積的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java用接口、多態、繼續、類盤算三角形和矩形周長及面積的辦法正文
本文實例講述了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法式設計有所贊助。