线程 class Java 的继承问题

Inheritance issues with thread class Java

我有这个话题 class:

class tCallTime implements Runnable {
  private Thread t;
  private String threadName;
  public tCallTime(String name) {
    threadName = name;
    println("Creating " +  threadName );
  }
  tCallTime() {
  
  }
  void codeToRun() {
    //Override This
    callTime();
  }

  public void run() {
    println("Running " +  threadName );
    try {
      codeToRun();
      Thread.sleep(0);
    } 
    catch (InterruptedException e) {
      println("Thread " +  threadName + " interrupted.");
    }
  }

  public void start () {
    if (t == null) {
      t = new Thread (this, threadName);
      t.setPriority(10);
      println("Started " + threadName +  " with priority " + t.getPriority());
      t.start ();
    }

我试图通过这样做继承:

class tCalcVertex extends tCallTime{
  @Override
  void codeToRun(){
  
    print("test");
  }
}

然后我尝试使用以下代码运行它:

  tCallTime thread = new tCallTime("Thread-1");
  thread.start();
  tCalcVertex thread2 = new tCalcVertex("Tread-2");
  thread2.start();

然后编译器告诉我“构造函数“tCalcVertex(String)”不存在” 我将如何继承这个 class 而不必重写整个 class

好吧,编译器是正确的,没有构造函数 在你的 class tCalcVertex 中接受一个字符串。它的父class中只有一个。构造函数不会自动继承,您必须为层次结构中的每个 class 显式定义它们:

class tCalcVertex extends tCallTime {
  public tCalcVertex(String name) {
    super(name);
  }

  @Override
  void codeToRun() {
    print("test");
  }
}

PS Java 命名约定 name classes 在 PascalCase 中以大写字母作为第一个字符。遵守这个约定可以让其他程序员更容易快速理解您的代码。