【问题标题】:Inheritance issues with thread class Java [duplicate]线程类Java的继承问题[重复]
【发布时间】:2020-12-06 23:36:30
【问题描述】:

我有这个线程类:

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)”不存在” 我将如何从这个类继承而不必重写整个类

【问题讨论】:

  • 你至少需要一个构造函数来传递线程名称。

标签: java inheritance multiple-inheritance


【解决方案1】:

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

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

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

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

【讨论】:

  • 感谢关于 PascalCase 用于 c++ 命名约定的评论,所以这是一个很好的信息
猜你喜欢
  • 2016-07-24
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2014-08-29
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多