Every time I create a new object, the attribute returns to zero

I create the class Ratingas follows:

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(for example):

 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 string System.out.printlnis just the last object RatingI created. I do not know why this is happening. Debugging print statements in the constructor assumes that the count returns to zero every time I create a new object.

+4
source share
3 answers

Change the variable declaration to private static int count;

Explanation

, count , static. , .

, .

+3

count , , , count, int , 0. static, Rating:

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

    // instance variables, constructor, methods, etc
+3

static :

  • ( ) static.
  • static .
  • static ( ).
  • static - ( , ).

The modifier staticindicates that the array rating[]is common to all Ratingin the entire class, and not to a single object.

But countthere is no variable . therefore, each time an object is created, the countvalue of the variable becomes 0. Because it is individual for each object.

To avoid this (solution):

add a staticmodifier to count the variable. It should look like this:

private static int count;
+2
source

Source: https://habr.com/ru/post/1678033/


All Articles