java - 访问给定对象的值

标签 java oop

我想知道为什么我必须处理两种类型的参数;构造函数的参数和方法的参数。例如,我有一个简单的类,它将两个数字相加

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>

最佳答案

使用this关键字:

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

您也可以在非静态方法中使用 this 关键字。

关于您的编辑: addKalc 类的函数(并且不是成员),因此您只能将其作为函数调用:

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

关于java - 访问给定对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16759901/

相关文章:

java - 单击时如何只选择一个按钮 -QUIZ ANDROID

java - Controller 上的 Spring @RequestMapping

java - OSWAP ESAPI 中是否有用于 session 管理的 java 代码示例?

java - 基本面向对象设计java

oop - DDD 是浪费时间吗?

java - JEdi​​torPane,preferredSize 是否跟踪父宽度?

java - 复杂类型中的 XJC javaType 适配器

php - 如何在类中包含定义常量的文件(及其范围)

delphi - 调用从接口(interface)和另一个祖先继承的类的方法

javascript - 如何正确委托(delegate)类原型(prototype)