[Java] Changing array from another class
Ok so my question I'm hoping is pretty simple:
I have an Array from one class, lets call it squares. It generates 100 squares. I have another class called reset. I want reset to take the array from the other class and set all the locations to 0.
How would I go about something like this?
Re: Java Changing array from another class
This wrecks the object-oriented principle of encapsulation. Why not just create a method within Class A called resetArray that does the same job. Doing what you ask however can be accomplished by making said array public and then modifying it in the other class, but like I stated, that is a bad habit to get into.
Re: Java Changing array from another class
Code:
class blah
{
sometype array[100];
function reset()
{
for (int i = 0; i < 100; i++)
{
array[i] = 0;
}
}
}
blah var;
var.reset();
something along those lines.
Re: Java Changing array from another class
Why would you have a class to reset the array?!? Why not do what bone-you suggested above?!?
Code:
class myClass
{
int[] myArray = new int[100];
void reset()
{
for (int i = 0; i < myArray.length(); i++)
{
myArray[i] = 0;
}
}
}
class myProgram
{
myClass instanceOfClass = new myClass();
myClass.reset();
}
Re: [Java] Changing array from another class
Correct.
The complete OPPOSITE of OOP programming is creating a new class to store the function.
Here's a C# example (It should work with Java, seeing that I'm not using any C# libraries, except the Console.WriteLine)
PHP Code:
class MySquareArray
{
static int[] myarray = new int[1000];
public static void ResetValues(int[] array)
{
foreach(int i in myarray)
{
i = 0;
}
}
}
class MyOtherClass
{
static void Main()
{
//Example scenario...
foreach(int i in MySquareArray.myarray)
{
Console.WriteLine(i + "in myarray.");
}
Console.WriteLine("Now resetting!");
MySquareArray.ResetValues(MySquareArray.myarray);
Console.WriteLine("New values of myarray:");
foreach(int i in MySquareArray.myarray)
{
Console.WriteLine("New value of " + i + "in myarray.");
}
}
}