public class Ride {
public static String name;
public static int ticketsRequired;
public static float heightRequirement;
public Ride(String name, int ticketsRequired, float heightRequirement) {
this.name = name;
this.ticketsRequired = ticketsRequired;
this.heightRequirement = heightRequirement;
}
public static void main(String args[]) {
Ride coaster, tosser;
coaster = new Ride("Roller Coaster", 6, 4.25f);
tosser = new Ride("Tummy Tosser", 7, 4.9f);
}
}
It only takes the value of the last instance which is "tosser" no matter what I call, why is that? Did I mess up with the attributes?
解决方案
Your class variables are static, which means there's only once copy of each for the entire class. You are overwriting the values in your constructor with each new object you create.
To have different values for each object, they need to be not static:
public String name;
public int ticketsRequired;
public float heightRequirement;
The fact that they're public means that they are accessible from any other class.
But that's also a sign that your class isn't properly encapsulated. You can make your fields accessible, even if they're private, but defining public accessor methods, e.g. getName().
Example, with one of the variables:
private String name;
and
public String getName() { return name; }