I have a class set to return a string like so:
package TextRPG;
public class File {
static String file;
public static void setFile(String fileLocation) {
file = fileLocation;
}
public static String getFile(){
return file;
}
}
But when i try to call it like so:
PrintWriter save = new PrintWriter(File.getFile());
I get an Error. What am I doing wrong?
EDIT, the netbeans error is :
cannot find symbol
symbol: method getFile()
location: class File
You have shot yourself in the foot because you are ignoring the Java naming conventions.
Variable names should start with a lowercase letter. Thus:
The java compiler doesn’t care about this … but your foot shot happened because you declared a field called
Filein a class calledFile, and Java’s rules for disambiguating the name collision came up with a strange answer.(If you included the compiler error message, it would be easier to explain …)
There are a couple of other problems with this class:
The is very non-OO code. You have a static field and static methods for getting and setting it. This kind of thing is a bit “icky” … and will lead to problems if you need to reuse the code in another context, or implement unit tests, etcetera.
You are using the same name as a well-known standard class (
java.io.File). This could lead to problems later on if some other class in your application needs to use bothjava.io.Fileandtextrpg.File.You are also ignoring the convention about how to form a package name that is designed to avoid package name collisions.
Before you write more code, I strongly recommend that you read the Sun Java Coding Conventions. And unless you have a really really good reason not to, follow them. (“I couldn’t be bothered” is NOT a good reason, IMO.)
Ah. So the compilation error is in this:
and it is saying that it can’t find a method called
getFile()inFile.Without seeing the rest of that class, I can’t be sure. However, I suspect that you are importing
java.io.*… and THAT means that theFilein the code snippet will be referring tojava.io.File… which doesn’t have agetFile()method!