[英]My constructor is not working as expected due to some error in data types and I cannot figure out why
public void Question(int resID, Boolean answer){
this.mTextResId = resID;
this.mAnswerTrue = answer;
}
This is a constructor I have for a class and then I am trying to build a question like this: 这是我在一个类中使用的构造函数,然后尝试构建一个像这样的问题:
private Question q1 = new Question(R.string.question_americas, true);
and it gives me an error as follows: 它给我一个错误,如下所示:
Question() in Question cannot be applied to (int, Boolean) Question中的Question()无法应用于(int,Boolean)
public void Question(int resID, Boolean answer)
is not a constructor. 不是构造函数。
public Question(int resID, Boolean answer)
is a constructor. 是一个构造函数。
Adding the void
return type makes it a regular method instead of a constructor, which is why the compiler only finds the default parameter-less constructor Question()
when you try to instantiate your class. 添加void
返回类型使其成为常规方法,而不是构造函数,这就是为什么当您尝试实例化类时,编译器仅找到默认的无参数构造函数Question()
。
Have a look at oracle documentation page for better understanding of constructor. 查看oracle文档页面,以更好地了解构造函数。
A class contains constructors that are invoked to create objects from the class blueprint. 一个类包含构造函数,这些构造函数被调用以根据该类蓝图创建对象。 Constructor declarations look like method declarations—except that they use the name of the class and have no return type 构造函数声明类似于方法声明,只是它们使用类的名称并且没有返回类型
In your case, you have wrongly added void
as return type for constructor method. 在您的情况下,您错误地将void
添加为构造函数方法的返回类型。
For example, Bicycle
has one constructor: 例如, Bicycle
具有一个构造函数:
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
To create a new Bicycle
object called myBike
, a constructor is called by the new operator: 要创建一个名为myBike
的新Bicycle
对象,新操作符将调用一个构造函数:
Bicycle myBike = new Bicycle(30, 0, 8);
new Bicycle(30, 0, 8)
creates space in memory for the object and initializes its fields. new Bicycle(30, 0, 8)
在对象中创建内存空间并初始化其字段。
Following above example, your constructor should be 在上面的示例中,您的构造函数应为
public Question(int resID, Boolean answer){
this.mTextResId = resID;
this.mAnswerTrue = answer;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.