Java - are constructors static?
I just wrote a constructor like this:
public ArchivesManager(String identifier) {
String[] components = String.sp开发者_开发问答lit("\nNEW");
}
But there's an error message: non-static method split(java.lang.String) cannot be referenced from a static context
. I know that error message, but why is the constructor static?!
It's because split should be called on a String object. I.e.
String foo = "Hello, world";
String[] arr = foo.split(",");
I know that error message, but why is the constructor static?!
The constructor context is not static, but you explicitly invoked the split
method in a static context when you qualified it with the classname; i.e. String.split(...)
.
You probably meant to write this:
String[] components = identifier.split("\nNEW");
which invokes the method in the (non-static) context of the String
object passed as identifier
; i.e. it says which string should be split.
To answer the question in the title:
"Constructors are not members" [JLS index] so static isn't really an appropriate concept. Constructors are not members because they are not inherited (I wish static methods weren't inherited either). From a class file point of view, they are special instance methods that return void
. Bytecode calling the constructor first allocates the memory, duplicates the reference to that memory and then calls the constructor on one of those references. (If targeting 1.4 or later, for an inner class assignment of "outer this" and enclosing final
fields occurs before calling the constructor.)
because of this String.split("\nNEW");
split
isn't static method
you probably need
public ArchivesManager(String identifier) {
String[] components = identifier.split("\nNEW");//NOTE: components are local to const. this doesn't make sense
}
Instead of String.split("\nNEW");
you need to call identifier.split("\nNEW");
. You want to split the identifier object (which is of type string). Essentially what you've said there is "split the string class", which doesn't make sense and hence the compiler complains.
This error does not mean that your constructor is static. It means Split is not static method, you have to call this method from its object.
In fact, I don't know why the constructor is static by default. The book "Thinking in Java" says that, "Even though it doesn't explicitly use the static keyword, the constructor is actually a static method."
精彩评论