你如何在Java中定义构造函数?

时间:2015-12-12 04:25:44

标签: java object constructor compiler-errors undefined

我是Java的新手,所以我不确定我的代码到底是什么问题。我继续得到一个未解决的编译问题:构造函数Student()未定义。我一直在努力工作几个小时,但我不确定是什么问题。我很感激你的帮助。谢谢! This is the main class Here is the Student class

8 个答案:

答案 0 :(得分:1)

您正确创建了构造函数:

public Student (String n, char g, Date b, Preference p){
     name = n;
     gender = g;
     birthDay = b;
     pref = p;
}

但是,此构造函数仅适用于所有给定的参数。您正在尝试将没有参数的Student对象创建到构造函数中。这种情况称为默认构造函数

要制作这样的构造函数,你可以这样做:

public Student (){
     //some default initializations
}

答案 1 :(得分:1)

您正在使用

实例化学生
new Student()

这是错误的,因为您尚未定义不带参数的构造函数。

您可以通过定义新构造函数来修复它

public Student(){
   //Set default values here
}

或者使用你已经拥有的构造函数。

Student bestStudent = new Student("Bryan", 'm', ...);

答案 2 :(得分:1)

当您没有定义类时,Java为类提供了默认构造函数(在本例中为Student())。但是,由于定义了构造函数Student(String s,char c,Date d,Preference p),因此不会自动提供此默认构造函数。

您现在必须使用您指定的构造函数。或者在Student类中实现一个不接受参数的构造函数

public Student() { }

您可以使用它来使用默认变量调用其他构造函数。

public Student() {

     this("", '', null, null); //Assuming you code is made to handle such a situation
}

答案 3 :(得分:0)

您正在调用没有参数的新Student()。这称为默认构造函数。如果没有其他构造函数,则不必指定默认构造函数。但是如果你有另一个带参数的构造函数,那么你必须指定它。

您只需将其添加到学生班。

public Student(){
}

答案 4 :(得分:0)

您需要传递ngbp的值。

所以new Student("hi", 'a', new Date(), myPreference)

答案 5 :(得分:0)

将另一个名为no-argument constructor的构造函数添加到学生班级。因为在for循环中你使用的是没有任何参数的循环。而你还没有在Student课程中定义它。

只需添加以下行。

public Student() {
}

答案 6 :(得分:0)

在Student()中初始化变量时,它们应该有修饰符:

private String name; private char gender; private Boolean matched;

等;这可能是导致错误的原因。

答案 7 :(得分:0)

示例:如果您的类名为Main 所以你可以为这个类定义构造函数,如:

Main(){

}

有关构造函数的更多详细信息,请参阅this link

相关问题