سؤال

Hey this is a very simple question. Can I call a variable, in this case an array, from a void method? I have declared my arrays at the class level and initialized them in a void method. Not sure it I am doing this correctly but I am trying to call the array from another class. I am a beginner. Thank you for the help.

ex:

public class HeyThere{
    public double me[];

    public void yeahYou(int you){
        me = new me[69]
    }
}
هل كانت مفيدة؟

المحلول 2

Yes, since your class level array me is scoped as Public, you will be able to access it from another class after you instantiate the HeyThere class.

Ex:

public class HeyThereCaller
{
..
....
    public void SomeMethod()
    {
    ...
    ....
    HeyThere heyThereInstance = new HeyThere();
    double[] meArray = heyThereInstance.me;
    }
}

نصائح أخرى

Here you declarate a public variable (array)

public double me[ ];

and here you instantiate it in a method

me = new me[69]

HeyThere obj1; double a = obj1.me[0]; This is going to give an error in Java though, because me is not instantiated

Yes, you certainly can! Because me is public, you can access it from outside of the class in which it is stored.
Also, you spoke of accessing it from a void method. The return type of a method has no effect on the data it can access; void only means that the method doesn't return a value when called.
If you want to study how variables can be accessed in Java, there is some useful info on this page.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top