Java线程:run方法不读取实例方法。

huangapple go评论66阅读模式
英文:

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;
}

huangapple
  • 本文由 发表于 2020年3月15日 18:47:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/60692060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定