binary101
binary101

Reputation: 1023

Using Arrays from a different Class

public class NewClass { 
    int[] anArray = {1,2,3,4};
}

public class NewerClass {     
    public static void main(String[] args){
        sendToMethod(NewClass.anArray);
    } 
}

Obviously how i've written it above doesn't work, i was wondering how (if possible) it could be done?

Basically i want to have a class of arrays (NewClass) and want to be able to use them with the methods from the NewerClass whilst in the main method of NewerClass.

Its not essential, I'm simply playing around with ideas.

Upvotes: 0

Views: 105

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533880

You can do either

public class   NewClass { static int[] anArray = {1,2,3,4}; }

or

public class NewerClass { 
    public static void main(String[] args){  
        sendToMethod(new NewClass().anArray); 
    }
}

Upvotes: 1

Rob Hruska
Rob Hruska

Reputation: 120456

You could expose it via an accessor method:

public class NewClass {
    private int[] anArray = { 1, 2, 3, 4 };

    public int[] getAnArray() {
        return anArray;
    }
}

public class NewerClass {
    public static void main(String[] args) {
        NewClass myNewClass = new NewClass();
        sendToMethod(myNewClass.getAnArray());
    }
}

Upvotes: 2

jlordo
jlordo

Reputation: 37843

It would work if you had it like this:

public class NewClass {
    public static final int[] anArray = {1,2,3,4};
    // final is optional.
}

but I don't know what you are trying to achieve.

Upvotes: 2

Related Questions