定义类Shape表示一般二维图形。Shape具有抽象方法area和perimeter,分别计算形状的面积和周长。试定义一些二 维形状类(如矩形、三角形、圆形等),这些类均为Shape类的子类。
publicabstractdoublearea();
publicabstractdoubleperimeter();
}
classRectangleextendsShape{//矩形
privatedoublewide;//宽
privatedoublelongs;//长
publicRectangle(){
}
publicRectangle(doublewide,doublelongs){
super();
this.wide=wide;
this.longs=longs;
}
publicdoublearea(){
returnthis.longs*this.wide;
}
publicdoubleperimeter(){
return(this.longs+this.wide)*2;
}
}
classTriangleextendsShape{//三角形
privatedoubleedgea;//边长
privatedoubleedgeb;//边长
privatedoubleedgec;//边长
publicTriangle(){
}
publicTriangle(doubleedgea,doubleedgeb,doubleedgec){
super();
this.edgea=edgea;
this.edgeb=edgeb;
this.edgec=edgec;
}
publicdoublearea(){
returnthis.edgea*this.edgeb/2;
}
publicdoubleperimeter(){
returnthis.edgea+this.edgeb+this.edgec;
}
}
classRoundextendsShape{//圆形
privatedoubleradius;//半径
publicRound(){
}
publicRound(doubleradius){
super();
this.radius=radius;
}
publicdoublearea(){
returnthis.radius*this.radius*Math.PI;
}
publicdoubleperimeter(){
returnthis.radius*2*Math.PI;
}
}
publicclassTestDemo{
publicstaticvoidmain(Stringargs[]){
Shaperectangle=newRectangle(10.5,20.6);
Shapetriangle=newTriangle(10.1,20.2,30.3);
Shaperound=newRound(30.3);
System.out.println("矩形面积:"+rectangle.area()+",矩形周长:"+rectangle.perimeter());
System.out.println("三角形面积:"+triangle.area()+",三角形周长:"+
triangle.perimeter());
System.out.println("圆形面积:"+round.area()+",圆形周长:"+round.perimeter());
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。