user1304752
user1304752

Reputation: 1

access non-static variable from another class

I have a problem with access to an array which defines non-static in it's class.

The elements of this array added by totally another class(call it "add"),so I cannot reach this class too. In my class I need to get the array from "A" class(which have the array) which filled from "add". Because of it is not static, when I make new attribute of this "A" class is make new object so forget the fill one.

My question; is there any way to get this non-static array with not lose it's elements?

Upvotes: 0

Views: 2240

Answers (2)

Robbie McCorkell
Robbie McCorkell

Reputation: 11

It is hard to tell from your description, but perhaps you just need to add a 'getter' method to the class containing the array you want, and call that method on the object containing the array from the class you want to access the array from.

i.e.

public 'ArrayType' getArray() {
    return array;
}

Replacing 'ArrayType' with the type of your array and 'array' with the name of your array.

This will give you a reference to the array so that you can then perform actions on what's inside it.

If you weren't already aware, this is fairly standard practice when you need access to an instance variable of an object from another class.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500535

Because of it is not static, when I make new attribute of this "A" class is make new object so forget the fill one.

Well yes - you'll need the instance that the values were added to. We can't tell you how to do that, as we don't know nearly enough about your code (after all, you haven't shown any of it). The fact that it's an array is irrelevant - the whole point of instance variables is that each instance has its own set of variables, to represent the state of that object. If you need the state of a particular object, you'll need a reference to that object.

As an aside, you shouldn't generally be accessing the variables of a different class directly - the variables should be private, with properties to access the data where appropriate. (That doesn't mean one property per variable, either. Often you don't want to expose the value directly at all - instead, you expose methods which act on the object as a whole. It's hard to be more specific without knowing what your object is meant to represent.)

Upvotes: 0

Related Questions