Walter Coggeshall Walter Coggeshall - 1 year ago 66
Java Question

Accessing Instance Variables from Another Class

If you want to get straight to the problem, skip this paragraph. As practice, I am trying to write a Java program that simulates an economy, and to that end wrote a company class. The idea was to have, say, a dozen of them, wrap their earnings into a normalvariate function, and that would be the economy.

I wrote a separate class to graph the companies' outputs using JFreeChart. However, I can't access the ArrayList that I write the amount of money for each year to from the graphing class. I understand the best way to do this is probably with getters, but it didn't seem to work, so if that is your advice, could you please provide an example? Thanks!

The company:

public class ServiceProvider implements Company {

public ArrayList getRecords(){
return records;

public ServiceProvider(){
money = 10000;
yearID = 0;
goodYears = 0;badYears = 0;
records = new ArrayList();

public void year() {

public void spend() {

public void printRecords() {
for(int i=0;i<records.size();i++){
String[] tmp = (String[]) records.get(i);
for(String a:tmp){
System.out.print(a+" ");



public void writeRecords(){
String[] toWrite = new String[2];
toWrite[0] = String.valueOf(yearID);
toWrite[1] = String.valueOf(money);

public void writeRecords(String toWrite){
String temp = "\n"+yearID+" "+toWrite;

public boolean getBankrupt(){
boolean result = (money < 0) ? true : false;
return result;


What I am trying to access it from:

public class grapher extends JFrame {
ArrayList records = s.getRecords();

public grapher(){
final XYDataset dataset = getCompanyData();

private XYDataset getCompanyData(){
XYSeries series;
for(int i=0;i<s.getRecords().length;i++){ //S cannot be resolved, it's instantiated in the main class.



The main class:

public class start {

public static void main(String[] args) {
ServiceProvider s = new ServiceProvider();
for(int i=0;i<10;i++){



P.S. Don't tell me what a mess Records are. I know.

Answer Source

Pass the instance of ServiceProvider as an argument to the grapher constructor and then it can pass it as an argument to getCompanyData().

Since the instance is created outside of the grapher class, there is no way for grapher to have the instance of ServiceProvider to work with unless you hand that instance to grapher.

BTW, make sure that whatever you do with that ArrayList in grapher that you don't change it. If you do, you'll be changing it in the ServiceProvider (since it's all just references to the same underlying ArrayList). That's probably not what you want to do. If you do need to change it, make a copy and work with the copy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download