0

コンストラクターとメソッドの 2 種類の引数を扱わなければならない理由を考えています。たとえば、2 つの数値を加算するこの単純なクラスがあります。

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>
4

4 に答える 4

1

thisキーワードを使用:

public int add(){
    return this.x + this.y + this.z;
}

this非静的メソッド内でもキーワードを使用できます。

あなたの編集について: クラスaddの関数(メンバーではないKalc)であるため、関数としてのみ呼び出すことができます:

System.out.println(k.add());
于 2013-05-26T13:53:40.907 に答える
1

あなたは以下を行うことができます

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 x+y+z;
    }
    public int multiply(){
        return x*y*z;
    }
    public static void main(String[] args) {
        Kalc k = new Kalc(4,5,6);
        System.out.println(k.add());
        System.out.println(k.multiply());
    }
}
于 2013-05-26T13:56:33.793 に答える
0

印刷する必要があると思います:

System.out.println(k.add());

それ以外の :

System.out.println(k.add);

2番目のケースではコンパイラは変数として表示k.addされaddますが、最初のケースadd()ではコンパイラadd()はKalcクラスで定義した関数として表示されます

于 2013-05-26T14:03:16.383 に答える
0

新しいオブジェクトとは?

所定の値でオブジェクトをインスタンス化しました。インスタンスメソッドで追加したい場合は、これを試してください

return this.x + this.y + this.z;
于 2013-05-26T13:56:10.230 に答える