I’m wondering why my policyNumber won’t increase by 1 every time the method is called.
when I run it, I get this.
I’m trying to get each Policy I add to automatically become PolicyNumber++.
Instead I’m getting the same number. Instead the same value gets assigned to all the new Policies I make.
run:
Policy #3 with amount $320.0
Policy #3 with amount $500.14
Policy #3 with amount $0.0
false
I’ve used this method before, I don’t understand why it’s not working now. Can someone shed some light please. Thank you!
main class
public class Assignment3 {
public static void main(String[] args) {
Policy p1 = new Policy(320);
Policy p2 = new Policy(500.14);
Policy p3 = new Policy(0);
System.out.println(p2.policyNumber);
p1.print(); System.out.println();
p2.print(); System.out.println();
p3.print(); System.out.println();
System.out.println(p1.isExpired());
}
}
Policy Class
public class Policy {
double amount;
public int policyCount;
public static int policyNumber;
public Policy(){
amount = 0;
policyCount = 1;
policyNumber=0;
}
public Policy(double a){
amount = a;
policyNumber ++;
}
public boolean isExpired(){
return false;
}
public void print(){
System.out.print("Policy #" + this.policyNumber + " with amount $" + this.amount);
}
}
The problem is that
policyNumberis not static. Therefore, it is an instance variable and has its own value for every object you instantiate. If you want to make it a class variable, you should declared it static:Check this official documentation about the difference between class and instance variables.
Additionally, you have to assign the static counter to an instance variable. If you just use the static variable, all your instances will have the value of the class variable. If you want to assign a value to each instance, you have to copy the value of the class variable to an instance variable.
Then you print method should look like this:
Be also aware that instance variables should normally be private to obey the information hiding principle.