0
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.

1
  • 2
    Also you can have a look 'java encapsulation' 'java access modifiers' keywords from stackoverflow. Commented Nov 29, 2012 at 14:34

3 Answers 3

2

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());
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Whilst playing around, i used this: sendToMethod(NewClass.class.newInstance().anArray); and it seems to work? Your code looks nicer though...
The way you did it there would be a bit roundabout, and isn't much different from (new NewClass()).anArray.
@qwertyRocker it's definitely better to do it the way @RobHruska describes, do not use NewClass.class.newInstance()
Ok, thanks for your help :D I think i'm going to give them accessor methods, seems more sensible and easier to read.
2

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.

Comments

1

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); 
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.