Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

new to java and have a question about getters and setters 1

Status
Not open for further replies.

csphard

Programmer
Apr 5, 2002
194
US
I created this class and I do not understand why this returns a 0 versus the 1 I am sending?

Thanks
public class myTest
{
private int myNumber;

public myTest()
{
int myNumber;
}

public int getMyNumber() {
return myNumber;
}
public void setMyNumber(int d) {
this.myNumber = myNumber;
}



public static void main(String[] args)
{

myTest mt = new myTest();
mt.setMyNumber(1);
System.out.println(mt.getMyNumber());
}
}
 
Argument of your function setMyNumber() is d and in the body you have
this.myNumber = myNumber
You have to change it either to
Code:
public void setMyNumber(int d) {
  this.myNumber = d;
}
or
Code:
public void setMyNumber(int myNumber) {
  this.myNumber = myNumber;
}
 
public void setMyNumber(int d) {
this.myNumber = myNumber;
}

in your code above you are not using the value that you have passed in "d". you are simply assigning a non-static int variable to itself.
and the reason behind why it is printing value "0" is that when a primitive veriable gets a memory inside an refrenced variable it is initialized to its default value of its datatype.And the default value of int datatype is "0".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top