我需要使用默认构造函数创建一个方法,该方法将name
设置为空字符串,并将credits
和contactHours
都设置为零。怎么做?谢谢,彼得。
答案 0 :(得分:11)
方法没有构造函数...类。例如:
public class Dummy
{
private int credits;
private int contactHours;
private String name;
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
// More stuff here, e.g. property accessors
}
您实际上没有设置来设置credits
或contactHours
,因为int
类型默认为0,无论如何。
你可能想要至少一个带有初始值的构造函数 - 在这种情况下,你的无参数构造函数可以委托给它:
public class Dummy
{
private String name;
private int credits;
private int contactHours;
public Dummy()
{
this("", 0, 0);
}
public Dummy(String name, int credits, int contactHours)
{
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// More stuff here, e.g. property accessors
}
答案 1 :(得分:3)
public class Test {
private String name;
private int credits;
private int contactHours;
public Test {
this( "", 0, 0);
}
public Test (String name, int credits, int contactHours) {
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// more code here
}
答案 2 :(得分:1)
public class Bibabu{
private String name;
private int credits;
private int contactHours;
public Bibabu(){
name = ""; // you could also write this.name and so on...
credits = 0;
contactHours= 0;
}
// more code here
}
答案 3 :(得分:0)
您不需要构造函数:
public class Dummy
{
private int credits = 0;
private int contactHours=0;
private String name="";
/*
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
*/
// More stuff here, e.g. property accessors
}
答案 4 :(得分:-1)
//constructor
public Account(int id, double balance, Person owner){
this.id = id;
this.balance = balance;
this.owner = owner;