JAVA 程式設計題解與上機指導(第四版) 第二章·識別符號、關鍵字和資料型別 2.12
阿新 • • 發佈:2018-11-04
/*2.12 設計實現一個MyGraphic類及子類,它們代表一些基本圖形,這些圖形包括矩形、三角形、圓、橢圓、菱形、梯形等。 試給能描述這些圖形所必需的屬性及必要的方法 **/ public class MyGraphic { String lineColor;//線條顏色 String fillColor;//填充顏色 MyGraphic(String lc,String fc){//圖形構造方法 this.lineColor=lc; this.fillColor=fc; } void print() { System.out.println("line color is "+this.lineColor+"\t fill color is "+this.fillColor); } public static void main(String args[]){ float rd=(float)4.5; MyCircle mc =new MyCircle(rd,"black","white");//定義“黑邊白心”圓 MyRectangle mr =new MyRectangle(4,6,"red","blue");//定義“紅邊藍邊”矩形 MyEllipse me=new MyEllipse(3,4,"green","gray"); System.out.println("Circle info: "); mc.print(); System.out.println("circumference is "+mc.calCircum());//圓周長 System.out.println("square is "+mc.calSquare());//圓面積 System.out.println("Rectangle info: "); mr.print(); System.out.println("circumference is "+mr.calCircum());//矩形周長 System.out.println("square is "+mr.calSquare());//矩形面積 System.out.println("Ellipse info: "); me.print(); System.out.println("circumference is "+me.calCircum());//矩形周長 System.out.println("square is "+me.calSquare());//矩形面積 } } class MyRectangle extends MyGraphic{ float rLong; float rWidth; MyRectangle (float rl, float rw, String lc, String fc){ super(lc,fc); this.rLong=rl; this.rWidth=rw; } float calCircum(){ return ((float)((this.rLong+this.rWidth))*2); } float calSquare(){ return ((float)(this.rLong*this.rWidth)); } }; class MyCircle extends MyGraphic{ float radius; float rWidth; MyCircle (float rd,String lc, String fc){ super(lc,fc); this.radius=rd; } float calCircum(){ return ((float)(this.radius*3.14*2)); } float calSquare(){ return ((float)(this.radius*this.radius*3.14)); } }; class MyEllipse extends MyGraphic{ float ra; float rb; MyEllipse (float a,float b,String lc,String fc){ super(lc,fc); this.ra=a; this.rb=b; } float calCircum(){// L=2πb+4(a-b return ((float)(this.rb*2*3.14+4*(this.ra-this.rb)));} float calSquare(){return ((float)(this.ra*rb*3.14));} };