I am building a class Rating
as following:
public class Rating{
//class attributes
private Movie movie;
private PremiumUser premiumUser;
private double rating;
private int id;
private int count;
protected static Rating [] ratings = new Rating [100];
public Rating(Movie movie, PremiumUser premiumUser, double rating){
this.movie = movie;
this.premiumUser = premiumUser;
this.rating = rating;
ratings[count] = this;
count += 1;
this.id = count;
}
public void setRating(int rating){
this.rating = rating;
}
public void setMovie(Movie movie){
this.movie=movie;
}
public void setPremiumUser(PremiumUser premiumUser){
this.premiumUser = premiumUser;
}
public int getID(){
return id;
}
public PremiumUser getPremiumUser(){
return premiumUser;
}
public Movie getMovie(){
return movie;
}
public double getRating(){
return rating;
}
@Override
public String toString(){
return ("Rating ID: " +id + "\nMovie: " + movie.getTitle() + "\nPremium User: " + premiumUser.getUsername() + "\nRating: " + rating);
}
}
But every time I create a new object Rating
(like so):
Rating rating1 = new Rating(movie1,marios, 9.0);
Rating rating2 = new Rating(movie2,zarko, 8.5);
Rating rating3 = new Rating(movie1, jdoe, 10);
System.out.println(Rating.ratings[0] + "" + Rating.ratings[1]);
What I get from the System.out.println
line is only the last Rating
object I created. I am not sure why that happens. Debugging print statements in the constructor suggest that count goes back to zero every time I create a new object.
count
is an instance member, and every time you instantiate a new object, it gets its own count
, initialized to int
's default, 0
. It should be a static
member, shared between all the Rating
s objects:
public class Rating {
private static int count; //here
protected static Rating [] ratings = new Rating [100];
// instance variables, constructor, methods, etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With