創建一個接口Shape,其中有抽象方法area,類Circle 、Rectangle實現area方法計算其面積並返回。又有Star實現Shape的area方法,其返回值是0,Star類另有一返回值boolean型方法isStar;在main方法里創建一個Vector,根據隨機數的不同向其中加入Shape的不同子類對象(如是1,生成Circle對象;如是2,生成Rectangle對象;如是3,生成S


題目補充:

創建一個接口Shape,其中有抽象方法area,類Circle Rectangle實現area方法計算其面積並返回。

又有Star實現Shapearea方法,其返回值是0Star類另有一返回值boolean型方法isStar

main方法里創建一個Vector,根據隨機數的不同向其中加入Shape的不同子類對象(如是1,生成Circle對象;

如是2,生成Rectangle對象;如是3,生成Star對象)。然后將Vector中元素依次取出,判斷其是否為Star類。如是返回其是個Star。否則返回其面積。

這個程序自己寫的,運行時報錯.但是我現在仍然不知道錯在哪

以下是程序:

 1 import java.lang.Math;
 2 interface Shape{
 3 abstract double Area();
 4 }
 5 class Rectangle implements Shape{
 6 private double x;
 7 Rectangle(){
 8 }
 9 Rectangle(double x){
10 this.x=x;
11 }
12 public double getX(){
13 return x;
14 }
15 public double Area(){
16 //area=getX()*getX();
17 return getX()*getX();
18 }    
19 }
20 class Circle implements Shape{
21 private double r;
22 Circle(){
23 
24 }
25 Circle(double r){
26 this.r=r;
27 }
28 public double getR(){
29 return r;
30 }
31 
32 public double Area(){
33 return 3.14*getR()*getR();
34 }
35 }
36 class Star implements Shape{
37 //private double r;
38 Star(){}
39 public double Area(){
40 return 0;
41 }
42 public boolean isStar(){
43 if(Area()==0)
44 return true;
45 else 
46 return false;
47 }
48 }
49 class Vector implements Shape{
50 public double Area(){
51 return 0;
52 }
53 }
54 public class Test {
55 public static void main(String args[]){
56 Shape[] s=new Vector[9];      //新建對象數組
57 int n;
58 for(int i=0;i<s.length;i++){
59 n=(int)(Math.random()*5);      //隨機函數產生隨機值
60 switch(n){
61 case 1:s[i]=new Circle();break;  //父類引用指向子類對象
62 case 2:s[i]=new Rectangle();break;
63 case 3:s[i]=new Star();break;
64 }
65 }
66 for(int i=0;i<s.length;i++){
67 if(s[i].Area()==0){
68 System.out.println(s[i]+"是個Star");
69 }
70 else System.out.println(s[i].Area());
71 }
72 
73 
74 }
75 }

調試報錯:

有沒有哪位大神賜教?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM