Reputation: 39
I have a linkedlist of Accounts, containing Employees and Managers (inheriting from Account). The problem is I have noticed the last added item seems to be overwritting the rest in the list. Why is it doing this? what I am doing wrong? thanks. I'll put my code below and console output. Sorry in advance if i am being really stupid and missing something obvious!
public class Database {
static List <Account> Accounts = new LinkedList<Account>();
public static void main(String[] args) {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
public static void list() {
for (Account u : Accounts) {
System.out.println(u);
}
}
Console Output is:
John, John, John
:(
Edit: code has been changed sorry guys!
public abstract class Account {
protected static String name;
protected static String passcode;
public User(String name, String passcode) {
this.name = name;
this.passcode = passcode;
}
}
Both manager and employee inherit from this so for manager:
public Manager(String name, String passcode) {
super(name, passcode);
}
Upvotes: 0
Views: 733
Reputation: 9316
Class variables (static) will only have a single instance that is shared between all instanciations of the class. That means that every time you say "this.name", it is semantically equivalent to saying "User.name", since "this" refers to the instance, not the class.
Change the class variables (static variables) to instance variables (non static variables) and everything will work as you expect.
Here is the documentation that explains class vs instance variables.
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Upvotes: 0
Reputation: 8640
Remove key word `static from declaration of fields and it will work fine.
static
variables are associated with the class, not with object. Which means those fields are shared between each instance of this class.
Upvotes: 4