public class Sample {
private int x;
public Sample(){
x=1;
}
public void Sample(double f){
this.x=(int)f;
}
public int getX(){
return x;
} public static void main(String[] args) {
Sample s=new Sample(5.2);
System.out.println(s.getX()); }}
老报错说没有定义构造方法,构造方法怎么个定义?
public Sample(double f){
x = f;
}
x=1;
} 构造函数无访问控制
this.x=(int)f;
} 改成
public Sample(double f){
this.x=(int)f;
}
this.x=(int)f;
}
是一个方法,不是构造方法,去掉void试试,应该行的!!
this.x=(int)f;
}
this.x=(int)f;
}
还有那个public void也去掉
private int x;
public Sample(){
x=1;
}
public void Sample(double f){
this.x=(int)f;
}
public int getX(){
return x;
} public static void main(String[] args) {
Sample s=new Sample();
System.out.println(s.getX()); }
} 或者:public class Sample {
private int x;
public Sample(){
x=1;
}
public Sample(double f){
this.x=(int)f;
}
public int getX(){
return x;
} public static void main(String[] args) {
Sample s=new Sample(5.2);
System.out.println(s.getX());
}
}
{
this.f = x;
}
x=1;
}
Sample(double f){
this.x=(int)f;
} 构造方法,就这么定义,没有为什么,是sun公司定的。
public void Sample(double f){
this.x=(int)f;
}
应写为
public Sample(double f){
this.x=(int)f;
}
就好了!
定义这样的方法。
Sample s=new Sample(); ---------> 这是new的无参数构造函数
Sample s=new Sample(5.2); --------> 这是new的有参数构造函数楼主加油!