简体   繁体   中英

How to use a method to reference a data type(array) that is created in a constructor

Sorry for the bad title...but I currently have a class Array and its constructor with a simple method getSize(). The constructor creates the array, is there a way to reference this array in the method without having to pass it as a param?

//constructor
Array(int n) {
    int arr[] = new int[n];
}
//method
static int getSize(int index) {

    //how do I reference the created array?
    return index;

}

SOLVED! THANK YOU

You can not reference a local variable declared in another method.

Instead, you can make it an instance member and reference it in these two methods.

Also, getSize should not be static since you can not reference a non-static member in a static method.

private int arr[];

Array(int n) {
    arr[] = new int[n];
}

int getSize(int index) {
    //reference the array here
    return index;
}

Why not declare the array as a class variable?

int arr[];

//constructor
Array(int n) {
    arr = new int[n];
}
//method
int getSize(int index) {

    //how do I reference the created array?
    return index;

}

You can access only the static variables in a static method. In order to access the array in this method either you have to make your array a static member but then you should initialize it in a static block.

Other thing which you can do is make the method non-static. Then you will be able to access the array inside the function without having to create an instance of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM