Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every time I instantiate new object, attribute goes back to zero

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.

like image 276
Marios Avatar asked Feb 05 '23 09:02

Marios


1 Answers

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 Ratings objects:

public class Rating {
    private static int count; //here
    protected static Rating [] ratings = new Rating [100];

    // instance variables, constructor, methods, etc
like image 93
Mureinik Avatar answered Feb 10 '23 05:02

Mureinik