java:不能在抽象类中使用构造函数

时间:2010-05-04 09:53:06

标签: java abstract-class red5 ischedulingservice

我在red5中为作业调度程序创建了以下抽象类:

package com.demogames.jobs;

import com.demogames.demofacebook.MysqlDb;
import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.scheduling.IScheduledJob;
import org.red5.server.api.so.ISharedObject;
import org.apache.log4j.Logger;
import org.red5.server.api.Red5;

/**
 *
 * @author ufk
 */
abstract public class DemoJob implements IScheduledJob {

protected IConnection conn;
protected IClient client;
protected ISharedObject so;
protected IScope scope;
protected MysqlDb mysqldb;

protected static org.apache.log4j.Logger log = Logger
    .getLogger(DemoJob.class);

protected DemoJob (ISharedObject so, MysqlDb mysqldb){

       this.conn=Red5.getConnectionLocal();
       this.client = conn.getClient();
       this.so=so;
       this.mysqldb=mysqldb;
       this.scope=conn.getScope();
 }

 protected DemoJob(ISharedObject so) {
   this.conn=Red5.getConnectionLocal();
   this.client=this.conn.getClient();
   this.so=so;
   this.scope=conn.getScope();
 }

 protected DemoJob() {
   this.conn=Red5.getConnectionLocal();
   this.client=this.conn.getClient();
   this.scope=conn.getScope();
 }

}

然后我创建了一个扩展前一个类的简单类:

public class StartChallengeJob extends DemoJob {

 public void execute(ISchedulingService service) {

   log.error("test");

 }

}

问题是我的主应用程序只能看到没有任何参数的构造函数。 我的意思是new StartChallengeJob() 为什么主应用程序看不到所有构造函数?

谢谢!

2 个答案:

答案 0 :(得分:8)

构造函数不是继承的。 StartChallengeJob 有效看起来像这样:

public class StartChallengeJob extends DemoJob {

  public StartChallengeJob() {
    super();
  }

  public void execute(ISchedulingService service) {    
    log.error("test");   
  }    
}

如果您希望所有超类构造函数签名都可用,则还需要在StartChallengeJob中包含这些构造函数:

public class StartChallengeJob extends DemoJob {

  public DemoJob (ISharedObject so, MysqlDb mysqldb) {
    super(so, mysqldb);
  }

  public DemoJob (ISharedObject so) {
    super(so);
  }

  public StartChallengeJob() {
    super();
  }

  public void execute(ISchedulingService service) {    
    log.error("test");   
  }    
}

答案 1 :(得分:4)

对于问题中显示的StartChallengeJob类,编译器会生成一个默认构造函数,它隐式调用基类的默认构造函数。

如果此默认行为不是您想要的,则需要在StartChallengeJob中显式定义一个或多个构造函数,然后调用所需的基类构造函数。例如。如果你想两者一个默认构造函数和一个参数化构造函数,你需要定义它们:

public class StartChallengeJob extends DemoJob {

 public StartChallengeJob(){
       // implicitly calls the base class default constructor: super();
 }

 public StartChallengeJob (ISharedObject so, MysqlDb mysqldb){
       super(so, mysqldb);
 }

 public void execute(ISchedulingService service) {

   log.error("test");

 }

}