I'm new to programming and I'm currently starting with java. I was wondering how to access elements of an object that I created. I thought I knew how but it doesn't seem to work. I'm constructing an object inside an inner class from a method, not in the inner class. I was wondering if you could give me some hints why it is not working when I want to access the values of the object that was just created. I mean can access the values, but they should be different from 0. It's as if my constructor didn't pass back the values. I did put my program in debugging and the values that are passed to the constructor are 0 , 2, 2. Thank you.
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
}
}
CodePudding user response:
nb = nb;
This doesn't do anything. It sets nb to itself.
You have 2 completely, utterly unrelated variables here. One is called int nb;
and is a field of your Build
class. The other is a method parameter, by total coincidence also named nb
.
You want to set the field, with the parameter value.
You have two options.
Stop using the same name. The method param 'takes precedence' (in java parlance: Shadows the field).
Use
this.nb
which refers to the field:this.nb = nb;
.
The second form is idiomatic java. Do that.