首先,我想为糟糕的标题道歉。我知道标题可以改进,但我不知道该用什么词合适。感谢对标题的帮助。
至于我的问题,我很好奇是否可以从“Friend”类中调用一个方法。我不确定如何解释我的问题,所以我希望这段代码能有所帮助。
public class Main {
public static void main(String args[]) {
int friends = 0;
while(friends < 3) {
new Friend().talk("Hello");
friends ++;
try {
Thread.sleep(500);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
// How do I call the 'goodbye()' method from one of the 'Friend' classes?
}
}
friend 类:
public class Friend {
int talk = 0;
public Friend() {
}
public void talk(final String word) {
Thread speech = new Thread() {
public void run() {
while(talk < 5) {
System.out.println(talk + ": " + word);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
talk ++;
}
}
};
speech.start();
}
public void goodbye() {
talk = 5;
}
}
如果我像上面显示的那样创建类对象,请告诉我是否可以从类中调用方法。另外,如果有人能告诉我从类中调用方法的正确术语,就像我展示的那样,那将是一个巨大的帮助。提前致谢!
最佳答案
在你的 main
方法中创建一个 Friend
类的实例
Friend f=new Friend();
然后调用它的方法
f.talk("Hello");
f.goodbye();
...
这样做您将引用同一个对象。在你的情况下,这就是你得到的
public static void main(String args[]) {
int friends = 0;
Friend f = new Friend();
while (friends < 3) {
f.talk("Hello");
friends++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
f.goodbye();
}
关于java - 如何从未在 Java 中实例化的类中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31361973/