[英]Make object array of sub-class
So it seems like I have to make an object array of a sub-class (Bicycle). 因此,似乎我必须制作一个子类(Bicycle)的对象数组。
I then add two objects to this.. and loop the array and print what each object is constructed from. 然后,我向此对象添加两个对象。并循环数组并打印每个对象的构造方法。
This sounds thoroughly confusing to me, and I'm unsure how to go about this. 这听起来让我完全困惑,我不确定该怎么做。
I'll also post the rest of my code, to make more sense. 我还将发布我的其余代码,以使其更加有意义。
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);
}
}
Change your main method to create an array of Bicycles, then add them by the index : 更改您的主要方法以创建一个Bicycles数组,然后按索引添加它们:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.