5

我有一个会议类,我想创建一个扩展会议的 BusinessMeeting 类。

这是我的会议课:

public class Meeting {

private String name;
private String location;
private int start, stop;

public Meeting(String name, String location, int start, int stop) {

    this.name = name;

    this.location = location;

    this.start = start;

    this.stop = stop;

}

这是我的商务会议课程:

public class BusinessMeeting extends Meeting {

    public BusinessMeeting() {

        super();

    }

}

在我的 BusinessMeeting 课程中,我收到错误消息:

类 Meeting 中的构造函数 Meeting 不能应用于给定类型;必需:String、String、int、int 找到:无参数

我不确定为什么会收到该错误消息。BusinessMeeting 类不应该继承我的 Meeting 类的所有变量吗?

4

7 回答 7

6
public class Meeting {
    public Meeting(String name, String location, int start, int stop) {

        this.name = name;

        this.location = location;

        this.start = start;

        this.stop = stop;

    }
}

现在说你想BusinessMeetingbusinessId.

public class BusinessMeeting {
    private Integer businessId;

    public BusinessMeeting(String name, String location, int start, int stop, int business) {
        // because super calls one of the super class constructors(you can overload constructors), you need to pass the parameters required.
        super(name, location, start, stop);
        businessId = business;
    }
}
于 2013-10-21T18:16:26.700 回答
5

您创建的构造函数接受 4 个参数,并且您在没有任何参数的情况下调用它。如果您希望它在没有参数的情况下也被初始化 - 将一个空构造函数添加到Meeting

 public Meeting(){}
于 2013-10-21T18:09:02.357 回答
2

您正在使用空参数调用超类构造函数:

public BusinessMeeting() {
        super();   
    }

但是你的超类有构造函数:Meeting(String, String, int, int).

使用super(),调用超类无参数构造函数(如果存在)。使用super(parameter list) ,调用具有匹配参数列表的超类构造函数。所以要么你必须向 Meeting 添加一个带空参数的构造函数,public Meeting(){}或者你需要调用super(String, String, int, int)

public class Meeting {
// your variable declaration
   public Meeting(String name, String location, int start, int stop) {
    // your assignment 
   }
   public Meeting(){}
}

public class BusinessMeeting extends Meeting {
    public BusinessMeeting()
    {
      // super(); un-comment if you need to check by commenting below
       super("name", "loc", 1, -1);
    }
}

签出:使用关键字 super

于 2013-10-21T18:15:17.233 回答
1

通过声明构造函数,您的Meeting类没有 0 参数构造函数,这是您尝试使用super();. 您需要调用与超类中可用的构造函数匹配的超级构造函数。

要解决此问题,请将 0 参数构造函数添加到Meeting类,或调用您已有的 4 参数构造函数。

于 2013-10-21T18:09:45.770 回答
1

正如 alfasin 所说,您已经创建了一个构造函数。标准规定,如果没有定义其他构造函数,则创建此构造函数。如果你想调用 super(),你必须自己创建一个无参数的构造函数

于 2013-10-21T18:10:36.110 回答
1

是和不是。这取决于您如何声明变量。

子类无法访问超类中的私有变量。通常您将受保护的 getter 和 setter-Methods 添加到超类中。这些方法可以在子类中用于访问变量。(有时草率的方法是将变量本身声明为受保护的)

子类不继承其父类的私有成员。但是,如果超类具有访问其私有字段的公共或受保护方法,则子类也可以使用这些方法。Java 继承网页

但是关于您提到的错误:您正在调用super(). 这意味着您正在调用超类的默认构造函数。由于您在超类中编写了自己的构造函数,因此没有默认构造函数。后者仅在您未定义构造函数时创建。

因此,当调用超类的构造函数时——在你的情况下它接受四个参数——你必须super()像这样传递这些参数:

super("a name", "a location", 0, 1)

于 2013-10-21T18:16:35.373 回答
0

您应该在会议类中添加带有空参数的构造函数,或者您可以在 BussinessMeeting 类中调用 super(name,location,start,stop) 而不是 super()

于 2013-10-21T18:11:16.843 回答