I’m new to java and I’m stuck with this. I have one BasePage class that contains a “global” List and an int value like this;
public class BasePage { public int number; public List<String> stringList = new ArrayList<>; }
Moreover, I’ve two classes that extend that page;
public class ClassA extends BasePage { public void addStringToList { stringList.add("String1"); number++; } }
And other:
public class ClassB extends BasePage { public void addStringToList { stringList.add("String2"); number++; } }
Then, when I access “stringList” and “number” after calling that who classes, the values are not “stacked” in BasPage. Is there a way to achieve this? Thanks!
Advertisement
Answer
Your fields aren’t static, meaning, each and every instance of a BasePage
object has its own ‘version’ of it. (and an instance of a ClassA
is a BasePage
instance as well; ClassA
extends BasePage
which means it’s a more specific kind of BasePage. It’s a BasePage with extra things, in other words).
Thus, when you run:
BasePage z = new BasePage(); ClassA a = new ClassA(); ClassB b = new ClassB();
You have 3 different number
s and 3 different stringList
.
You can reduce this down to having just one for the entire VM by making them static
but beware, this is almost universally derided as bad code style: You’ve created global state, which is hard to test, and makes code hard to read.
A better idea would be to have a separate class such that instances of it represent ‘an application’, ‘a library’, ‘a ledger’, or something similar: A thing that encompasses the idea of ‘a whole bunch of BasePage instances’.
This stringList
variable would then be in the library class, not the book class. Example:
Bad design
public class Book { private static int booksInLibrary = 0; private String title; public Book(String title) { this.title = title; booksInLibrary++; } }
Good design
public class Library { private final List<Book> books = new ArrayList<>(); public int countBooks() { return books.size(); } public void addBook(Book book) { books.add(book); } } public class Book { private final String title; public Book(String title) { this.title = title; } }