Call a method without arguments in Java
I have a code like this:
import com.eteks.sweethome3d.SweetHome3D;
import com.eteks.sweethome3d.model.Home;
public class Test extends SweetHome3D {
public static void main(String [] args) {
new Test().init(args);
}
@Override
public Home createHome() {
Home home = super.createHome();
// Modify home as you wish here
return home;
}
}
and I want to run my method through main. Do you know how I can do that? I have tried many ways like:
createHome();
super.createHome();
But it doesn't recognize this type. I also tried
Test test = new Test();
test.init(args);
test.createHome();
which doesn't create any error, but still, what I want is not done. And they advised me 开发者_开发技巧"You shouldn't call test.createHome(); directly"
Thanks in advance:)
The thing is that now it runs my application but when I put this
System.out.println("method called");
into my method, it is displayed twice...??? Why?
There is no problem in invoking test.createHome()
, and it is the way it should work.
In order to check whether the method is called you can put System.out.println("method called)
in the createHome()
method.
Your problem probably lies somewhere else, perhaps in the superclass.
The problem is the difference between static methods and instance methods. createHome is an instance method which means you have to have an instance of that class to call that method. That's why you can call createHome() from your test variable because test is an instance of Test. The main method is a static method, and it's associated with Class Test and it doesn't have an instance of Test to invoke that method on. A Class is a different piece of memory from the instances created from that Class. However, a Class can have methods and variables associated with it through the use of the static keyword.
Now why it's not working has probably more to do with your code and the assumptions it makes about when that method can be called. I suppose the init() method is doing some rather large and it's not ready to handle invocations to createHome() because the system hasn't fully started. Looks like a UI program so there might be some issues with timing and processing events.
It's hard to know why it's not working for you without specific errors.
精彩评论