题目
java题:计算三角形和矩形的周长和面积,要求用接口,多态,继承,类四种不同方法分别写程序
提问时间:2021-03-31
答案
接口和继承都是多态的一种表现形式,所以一个小程序可以解决所以的问题!
马上写出来
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();
}
举一反三
已知函数f(x)=x,g(x)=alnx,a∈R.若曲线y=f(x)与曲线y=g(x)相交,且在交点处有相同的切线,求a的值和该切线方程.
我想写一篇关于奥巴马的演讲的文章,写哪一篇好呢?为什么好
奥巴马演讲不用看稿子.为什么中国领导演讲要看?
想找英语初三上学期的首字母填空练习……
英语翻译
最新试题
- 1ln(x)^(1/x)=0 x等于几
- 2Wear the glasses!
- 3去加一笔什么字(除了丢),竞加一笔什么字(除了竟),李加一笔什么字(除了季)
- 4试在n≥4或n≤-5的n值中,求出所有使代数式2n²+n-29的值是某两个连续自然数的平方和的整数n.
- 5correspondence address是什么意思
- 6命题公式P→Q∧P是
- 7The days we had been looking forward to_____at last.A.come B came 选什么
- 8关于奥林匹克运动会的知识
- 9I don’t know (what) to do next.(Could)you give me (some)(advices)? A B C D
- 10I want to ____ ____ the music club because I like playing the piano.
热门考点
- 1因字加偏旁组成新字
- 2耳字加偏旁组字
- 31 could you please do _________ shopping with me A:any B:some C :much
- 41.This little boy is very shy,He only plays with his()
- 5写出红、黄、蓝和白色的词语(5个)
- 6某物体的质量等于它本身质量的百分之75再加上4分之3kg,这个物体的质量是多少?急求答案,急急急
- 71.In China,a person_____bow to others.
- 8已知函数y=f(x)的定义域为【0,2】,则函数f(2x-1)的定义域为
- 9文言文 阳城淀 译文
- 10Here ___ some juice and some wter.(be) Here____some juice and some apples.(be)