awawawaw
awawawaw

Reputation: 195

How do I access multiple objects from another method in the same class java?

Here's my code, I'm trying to access e1,e2,e3 in my getData() method but it's not working. How do I get my second method to recognize the first ones but keeping the methods separate?

public class Model {

    public Model() {
        loadData();
    }

    public void loadData() { 
        Employee e1 = new Employee("John Smith", "California, PA.", "Dr. Robertson junior.");

        Employee e2 = new Employee("Kyle Alston",  "State College, PA.", "SmithTown");

        Employee e3 = new Employee("Tommy Smith", "Baskeville, PA.", "Chicago");
        
      
    }
    public String getData(int n)  { 
        if(n == 1){
            return e1;

        }
        if(n == 2){
            return e2;

    }
        if(n == 3){
            return e3;

    }
        
        
        
    }
}

I tried Model data = new loadData().e1 but I don't think that works.

Thanks in advance. I'm not allowed to change the parameters.

Upvotes: 0

Views: 529

Answers (1)

user16632363
user16632363

Reputation: 1100

Use member variables to retain values from one method to the next.

public class Model {

    private Employee e1, e2, e3;

    public Model() {
        loadData();
    }

    public void loadData() { 
        e1 = new Employee("John Smith", "California, PA.", "Dr. Robertson junior.");
        e2 = new Employee("Kyle Alston",  "State College, PA.", "SmithTown");
        e3 = new Employee("Tommy Smith", "Baskeville, PA.", "Chicago");    
    }

    public String getData(int n)  { 
        if (n == 1) {
            return e1;
        }
        if (n == 2) {
            return e2;
        }
        if (n == 3) {
            return e3;
        }
        return null;
    }
}

For comparison, rewritten using a simple array. The benefit here is that getData is now independent of the number of employees.

public class Model {

    private Employee[] e;

    public Model() {
        loadData();
    }

    public void loadData() { 
        e = new Employee[3];
        e[0] = new Employee("John Smith", "California, PA.", "Dr. Robertson junior.");
        e[1] = new Employee("Kyle Alston",  "State College, PA.", "SmithTown");
        e[2] = new Employee("Tommy Smith", "Baskeville, PA.", "Chicago");    
    }

    public String getData(int n)  { 
        if (n <= 0 || n > e.length) {
           return null;
        }
        return e[n-1];
    }
}

I might consider using an ArrayList rather than an array, but the array is more fundamental in Java, which I think makes it a better choice for initial learning.

Upvotes: 4

Related Questions