Reputation: 301
I've got a class called Files
where I have a toString
method like so:
public String toString() {
String res = "[";
for (int i = 0; i < files.size(); ++i) {
if (i > 0) {
res += " ";
}
res += files.get(i);
}
return res + "]";
}
In a separate class called Homework
I have another toString method where I am trying to print the string that was returned in Files.toString()
. Right now my code looks like:
public String toString(){
String output = Files.toString();
return output;
}
But the error it's giving me is that it can't make a static reference to a non static method. Is there a way to make a non static reference? Both toString
methods are not static so I don't know why it is making a static reference.
Upvotes: 0
Views: 2616
Reputation: 567
You have to have an instance of Files class to be able to invoke it's non-static method.
Files f = new Files();
f.toString();
Upvotes: 0
Reputation: 2855
you want to use a files object not the Files class, the way you do it you call the method toString() from the class File wich you can't do because toString is not a static method, but you can call toString from an object based on the Files class.
Upvotes: 1
Reputation: 218828
This is a static reference:
Files.toString()
Because Files
is the name of the class. However, this is not a static method:
public String toString() {
If you're trying to call .toString()
on a specific instance of Files
then you need to call it on that instance, not on the class itself. For example, if the instance variable is called myFiles
then you'd do this:
public String toString(){
String output = myFiles.toString();
return output;
}
Where is your instance of Files
in your Homework
object? Or, if you don't have an instance, what are you trying to turn into a string?
Upvotes: 0
Reputation: 159754
This expresson
Files.toString()
refers to a static toString
method - you need to use an instance of Files
Files files = new Files();
...
String output = files.toString();
Upvotes: 2
Reputation: 4551
Because toString
in Files
is not a static method but you're referencing it in a static way. Make an object of Files
and then access it like new Files().toString();
Upvotes: 1