Reputation: 157
I am creating an array in the class with main method
Word attempts = new Word (26);
Field in class Word is
private String [] attempts;
Constructor in class Word is
public Word (int a){
attempts = new String [a];
create(attempts);
}
Where create is a method that makes every array element an empty String ("")
. In class Word I've also got a getAttempts()
method for accessing the attempts array. Now, I want to make class Letter where i pass the before created array Word []
in a for loop. I tried with Word.getAttempts()[i], but I get an error Cannot make a static reference to the non-static method getAttempts() from the type Word
. To my understanding when a method is static, you do not have to create an object before calling the method. I have no idea how to pass the array created in Main method to this Letter class. Any help?
edit: Here is my Word class
public class Word {
private String [] attempts;
public String[] getAttempts() {
return attempts;
}
public void create (String [] attempts){
for (int i=0; i<attempts.length; i++){
attempts[i]="";
}
}
public Word (int a){
attempts = new String [a];
create(attempts);
}
}
To sum up, I am creating an array in class with Main method that is type of Word, and I want to pass that array to separate class Letter.
Upvotes: 2
Views: 2733
Reputation: 38809
Word.getAttempts()
... would be how you would access a static method named getAttempts
in class Word
. However, your method getAttempts
is not static: it works on instances of your class.
Assuming you define such an instance as follows:
Word word = new Word(26);
Then, provided the method is public, you can access the array with:
String[] attempts = word.getAttempts();
To my understanding when a method is static, you do not have to create an object before calling the method.
Yes, but your method is not static.
I understand that, but after defining Word array in Main method, how can i access it in a new class?
You pass objects through methods or constructors, which allow other objects to interact with it using the API defined by public methods.
Now, I want to make class Letter where i pass the [...] array
Define a class named Letter
, and a constructor which accept an object of class Word
.
class Letter
{
private final Word word;
public Letter (Word word) {
this.word = word;
}
}
And in main
:
public static void main (String[] args)
{
Word word = new Word(26) ;
Letter letter = new Letter(word);
}
You could pass directly word.getAttempts()
, but then you are directly working with the internal values of another class, which is bad style. Better work with instances of Word
through its public methods than by directly accessing its private data.
Upvotes: 2