2015-09-20 147 views
0

所以看起來我必須創建一個子類(Bicycle)的對象數組。創建子類的對象數組

然後我添加兩個對象到這個..並循環數組並打印每個對象的構造。

這聽起來令我感到困惑,我不確定如何去做這件事。

我還會發布我的代碼的其餘部分,以便更有意義。

MAIN:

package javaapplication4; 

public class JavaApplication4 { 

    public static void main(String[] args) { 

     Bicycle myBike = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame"); 
     System.out.println(myBike);   
    } 
} 


package javaapplication4; 

public class Implement { 

    String name; 
    boolean hasMovingParts; 
    String constructedFrom; 

    public Implement() { 
    } 

    public Implement(String name, boolean hasMovingParts, String constructedFrom) { 
    this.name = name; 
    this.hasMovingParts = hasMovingParts; 
    this.constructedFrom= constructedFrom; 
    } 

    public String getName() { 
    return name; 
    } 

    public boolean getMovingParts() { 
    return hasMovingParts; 
    } 

    public String getConstructedFrom(){ 
    return constructedFrom; 
    } 

    public class Bicycle extends Implement { 
    public int seatNumber; 

    public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) { 
    this.seatNumber = seatNumber; //takes the value you pass as parameter 
    this.name = name; // and stores it into the instance variable 
    this.hasMovingParts = hasMovingParts; 
    this.constructedFrom = constructedFrom; 
    } 

    @Override 
    public String toString(){ 
     return String.format("*Vehicle Statistics* Seats: %d, Name:" + 
      " %s, Contains Moving Parts: %b, Materials: %s", 
       seatNumber, name, hasMovingParts, constructedFrom); 
    } 
} 
} 


package javaapplication4; 

public class Bicycle extends Implement { 
    public int seatNumber; 

    public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) { 
    this.seatNumber = seatNumber; 
    this.name = name; 
    this.hasMovingParts = hasMovingParts; 
    this.constructedFrom = constructedFrom; 
    } 

    @Override 
    public String toString() { 
    return String.format("*Vehicle Statistics* Seats: %d, Name:" + 
     " %s, Contains Moving Parts: %b, Materials: %s", 
     seatNumber, name, hasMovingParts, constructedFrom); 
    } 
} 
+2

歡迎來到Stack Overflow!請閱讀指南[我如何提出一個好問題](http://stackoverflow.com/help/how-to-ask),尤其是關於最小,完整和可驗證示例(MCVE)的部分。這將幫助你爲自己解決問題。如果你這樣做,仍然卡住,你可以回來發佈你的MCVE,你試過的,以及結果是什麼,所以我們可以更好地幫助你。 – JeffC

回答

0

更改您的主要方法創建自行車的數組,然後通過索引添加它們:

public static void main(String[] args) { 

    Bicycle[] bicycles = new Bicycle[2]; 
    bicycles[0] = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame"); 
    bicycles[1] = new Bicycle(1, "Orah XMB", true, "Handlebars, Tyres, Frame"); 

    for (Bicycle bicycle : bicycles){ 
     System.out.println(bicycle); 
    } 
}