我想知道为什么我必须处理两种类型的参数;构造函数的参数和方法的参数。例如,我有一个简单的类,它添加了两个数字
class Calc{
private int x = 6;
private int y;
private char z = 'z';
public int getx(){
return x;
}
public char selfrecur(){
return this.z;
}
public int add(int one,int two){
return one + two;
}
public static void main(String[] args) {
Calc gx = new Calc();
System.out.println(gx.x);
System.out.println(gx.add(44,3));
System.out.println(gx.selfrecur());
}
}
那行得通,哇,不是那么好。现在,我有了让构造函数提供参数的想法,而函数的工作将是进行繁重的计算。例如在我的课上 Kalc
class Kalc{
//** This example won't work **
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3){
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return newObject.x + newObject.y + newObject.z;
//Gets the values of a new object and add them up
}
public int multiply(){
return newObject.x * newObject.y * newObject.z;
//Gets the values of a new object and multiply them
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add());
System.out.println(k.multiply());
}
}
我一直在这里http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html寻找线索,但到目前为止还没有。这甚至可能吗?
编辑
class Kalc{
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3){
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return this.x + this.y + this.z;
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add);
}
}
错误
C:\ja>javac Kalc.java
Kalc.java:17: error: cannot find symbol
System.out.println(k.add);
^
symbol: variable add
location: variable k of type Kalc
1 error
C:\ja>