英文:
Java Thread: Run method does not read Instance methods
问题
public class Battle extends Thread {
private Instructor instructor1;
private Instructor instructor2;
public Battle(Instructor instructor1, Instructor instructor2) {
this.instructor1 = instructor1;
this.instructor2 = instructor2;
}
public void run() {
System.out.print(instructor1.getCurrentHP()); // DOES NOT WORK
}
public static void main(String[] args) {
Instructor instructor1 = new Instructor("Big Omar Latif", 999, 145, 180, 4000);
Instructor instructor2 = new Instructor("Small Ali Raza", 400, 185, 230, 1200);
Battle x = new Battle(instructor1, instructor2);
System.out.print(instructor1.getCurrentHP()); // THIS WORKS
x.start();
}
}
在这个代码片段中,我已经进行了适当的翻译。如果您有任何进一步的问题或需要帮助,请随时问我。
英文:
public class Battle extends Thread{
private Object instructor1;
private Object instructor2;
public Battle(Object instructor1, Object instructor2){
this.instructor1 = (Instructor)instructor1;
this.instructor2 = (Instructor)instructor2;
}
public void run(){
System.out.print(instructor1.getCurrentHP());//DOES NOT WORK
//}
}
public static void main(String[] args){
Instructor instructor1 = new Instructor("Big Omar Latif", 999, 145, 180, 4000);
Instructor instructor2 = new Instructor("Small Ali Raza", 400, 185, 230, 1200);
Battle x = new Battle(instructor1, instructor2);
System.out.print(instructor1.getCurrentHP()); //THIS WORKS
x.start();
}
}
So i have a class where i have defined method, .getCurrentHP() of the instructor when i print it in the main function, it works. But when i print it in the run method, it says symbol not found. whys that? how can i call my method?
答案1
得分: 1
The getCurrentHP() method works for objects of type Instructor. So you need to change instructor1 & instructor2 from object to Instructor as shown below
public class Battle extends Thread{
private Instructor instructor1;
private Instructor instructor2;
public Battle(Instructor instructor1, Instructor instructor2){
this.instructor1 = instructor1;
this.instructor2 = instructor2;
}
英文:
The getCurrentHP() method works for objects of type Instructor. So you need to change instructor1 & instructor2 from object to Instructor as shown below
public class Battle extends Thread{
private Instructor instructor1;
private Instructor instructor2;
public Battle(Instructor instructor1, Instructor instructor2){
this.instructor1 = instructor1;
this.instructor2 = instructor2;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论