悪いタイトルをお詫びすることから始めたいと思います。タイトルを改善できることは知っていますが、適切な用語がわかりません。タイトルのヘルプをいただければ幸いです。
私の質問については、「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?
}
}
フレンドクラス:
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;
}
}
上に示したようにクラスオブジェクトを作成した場合、クラスからメソッドを呼び出すことができるかどうかを教えてください。また、私が示したようなクラスからメソッドを呼び出すための適切な用語を誰かに教えてもらえれば、それは大きな助けになるでしょう。前もって感謝します!
静的があなたが探しているものではない場合、あなたのコメントとそれがコードのどこに存在するかのために私は信じがちです
'Friend'クラスの1つから 'goodbye()'メソッドを呼び出すにはどうすればよいですか?
次に、あなたの質問は、あなたが本当にオブジェクトをインスタンス化しているという意味で誤解を招きます。この例では、Friendsを作成し、それらを配列に格納します。
public static void main(String args[]) {
int count = 0;
//you can store reference to Friend in an array
Friend[] friends = new Friend[3];
//in the loop, you make 3 new Friends
while (count < 3) {
friends[count] = new Friend();
count++;
}
//Since they're instantiated and stored in the array, you can call their methods later
friends[0].goodbye();
//or
friends[1].goodbye();
//or
friends[2].goodbye();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加