如何从对象访问元素? java
How to access element from an object? java
我是编程新手,目前正从 java 开始。我想知道如何访问我创建的对象的元素。我以为我知道怎么做,但它似乎不起作用。我正在通过方法在内部 class 内部构造一个对象,而不是在内部 class 中。我想知道您是否可以给我一些提示,为什么当我想访问刚刚创建的对象的值时它不起作用。我的意思是可以访问这些值,但它们应该不同于 0。就好像我的构造函数没有传回这些值一样。我确实将程序置于调试状态,传递给构造函数的值为 0、2、2。谢谢。
public class puzzle{
public class Build{
int nb, piece, length;
public Build(int nb, int piece, int length){
//In debug I see that the values are passed, but when I print in the method the values printed are all 0.
nb = nb;
piece = piece;
length = length;
}
}
public void rectangle(String book){
//line of code where I do manipulations
Build box = new Build(beginning, tv, book.length());
System.out.println(box.nb);
System.out.println(box.piece); //should print a value different then 0
System.out.println(box.length); //should print a value different then 0
}
}
nb = nb;
这没有任何作用。它将 nb 设置为自身。
这里有 2 个完全不相关的变量。一个叫做 int nb;
,是你的 Build
class 的一个字段。另一个是方法参数,巧合的是也命名为 nb
.
您要设置字段,参数值。
你有两个选择。
停止使用相同的名称。方法参数 'takes precedence'(用 java 的说法:阴影字段)。
使用 this.nb
引用字段:this.nb = nb;
.
第二种形式是惯用的java。这样做。
我是编程新手,目前正从 java 开始。我想知道如何访问我创建的对象的元素。我以为我知道怎么做,但它似乎不起作用。我正在通过方法在内部 class 内部构造一个对象,而不是在内部 class 中。我想知道您是否可以给我一些提示,为什么当我想访问刚刚创建的对象的值时它不起作用。我的意思是可以访问这些值,但它们应该不同于 0。就好像我的构造函数没有传回这些值一样。我确实将程序置于调试状态,传递给构造函数的值为 0、2、2。谢谢。
public class puzzle{
public class Build{
int nb, piece, length;
public Build(int nb, int piece, int length){
//In debug I see that the values are passed, but when I print in the method the values printed are all 0.
nb = nb;
piece = piece;
length = length;
}
}
public void rectangle(String book){
//line of code where I do manipulations
Build box = new Build(beginning, tv, book.length());
System.out.println(box.nb);
System.out.println(box.piece); //should print a value different then 0
System.out.println(box.length); //should print a value different then 0
}
}
nb = nb;
这没有任何作用。它将 nb 设置为自身。
这里有 2 个完全不相关的变量。一个叫做 int nb;
,是你的 Build
class 的一个字段。另一个是方法参数,巧合的是也命名为 nb
.
您要设置字段,参数值。
你有两个选择。
停止使用相同的名称。方法参数 'takes precedence'(用 java 的说法:阴影字段)。
使用
this.nb
引用字段:this.nb = nb;
.
第二种形式是惯用的java。这样做。