初学java 编写求正方形/长方形的周长与面积,正方体/长方体 的表面积与体积
本帖最后由 hcz888 于 2021-3-9 01:14 编辑复习了九天java,分享一下代码package aaa;
public interface PlaneGraphics2 {
public abstract double area();
public abstract double perimeter();
public abstract void print();
}
package aaa;
public interface SolidGraphics1 {
public abstract double volume();
}
package aaa;
public class Rectangle2 implements PlaneGraphics2
{
protected double length;
protected double width;
Rectangle2(double length,double width){
this.length=length;
this.width=width;
}
Rectangle2(double length)
{
this.length=length;
}
Rectangle2(){
this(0,0);
}
Rectangle2(Rectangle2 r1)
{
this(r1.length,r1.width);
}
public double perimeter()
{
return 2*(this.length+this.width);
}
public double area(){
return this.length*this.width;
}
public void print(){
if(this.length==this.width){
System.out.println("正方形,"+"边长是:"+this.length);
}
else{
System.out.println("长方形,"+"长是:"+this.length+"宽是:"+this.width);
}
System.out.println("周长是:"+this.perimeter()+"面积是:"+this.area());
}
}
package aaa;
public class Cuboid1 extends Rectangle2 implements SolidGraphics1 {
protected double height;
Cuboid1(double length,double width,double height){
this.length=length;
this.width=width;
this.height=height;
}
Cuboid1(Rectangle2 r1,double height){
super(r1.length,r1.width);
this.height=height;
}
Cuboid1(double length){
this(length,length,length);
}
Cuboid1(){
this(0,0,0);
}
public double perimeter(){
return 0;
}
public double area(){
return length*width*2+length*height*2+width*height*2;
}
public double volume() {
return super.area()*this.height;
}
public void print(){
if(this.length==this.width&&this.width==this.height){
System.out.println("一个正方体"+",边长为"+this.length);
}
else{
System.out.println("一个长方体"+",长为"+this.length+
"宽为"+this.width+"高为"+this.height);
}
System.out.println(",体积为"+this.volume()+"表面积"+this.area());
}
}
package aaa;
public class C_ex {
public static void main(String args[])
{
PlaneGraphics2 s1=new Cuboid1(10,10,10);
s1.print();
PlaneGraphics2 s2=new Rectangle2(10,100);
s2.print();
}
}
这个挺简单的,谢谢楼主 C_ex
有这么定义类的? 给新入坑的小伙伴鼓励 本帖最后由 fht000 于 2021-3-9 09:04 编辑
你这SolidGraphics1不应该继承PlaneGraphics2接口吗?或者Cuboid1同时实现这2个接口。反而Cuboid1去继承Rectangle2类,不符合面向接口编程的理念 {:1_927:}java小伙伴
页:
[1]