Reputation: 403
I want to ask about the effect of static
: I made a class music
and used static
when declaring my music class variables. But when I run my main class to print out music data, it always prints out the same value from the last data I put in in my main class.
my class music :
private static String name, genre;
private static int price;
public music(String a, String b, int c){
name = a;
genre = b;
price = c;
}
my main class code:
music a1 = new music("A","A",1);
music a2 = new music("B","B",2);
music a3 = new music("C","C",3);
music a4 = new music("D","D",4);
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(a4);
my output :
Music[Nama = D, Genre = D, harga = 4]
Music[Nama = D, Genre = D, harga = 4]
Music[Nama = D, Genre = D, harga = 4]
Music[Nama = D, Genre = D, harga = 4]
I know how to fix it - I just need to remove static
from variable declaration - but I want to know why static
makes so much difference and makes my code wrong.
Upvotes: 0
Views: 68
Reputation: 1510
Static variable is variables that are common to all objects. Meaning every instance will share the same variable. For more information, refer Understand Class Member
Upvotes: 2
Reputation: 4391
A static variable belongs to the class not the objects that your are creating. So by making a variable static all objects that are created do not have that specific variable. They have access to the static variable that belongs to the class.
So any time they update the variable since it's static they are updating the variable that lives in the class.
By removing static
from variable declaration removes it from the class and makes it part of each object. So if you remove the static
part each object you created will have its own variable.
Upvotes: 1
Reputation: 3439
I think you have not Read about static instance of the class. just read that about static and short idea about static is first read about static keyword first. static keyword
static variable will have single copy threw out of the System. and only one copy of that instance will be exist.
later you can modify it but can not be assign new it will be override the same variable.
Upvotes: 1
Reputation: 8207
Static
variables are class variables and have the single instance . In your case they have the updated values as your overriding them.
To get the result with the values you are passing for the constructor you need to instantiate the class with different objects , so remove the static keyword from the variables
Upvotes: 0
Reputation: 394116
A static variable belongs to the class instead of a single instance of the class. Therefore all instances of the class that update that static member are updating the same variable and overriding each other.
Upvotes: 4