INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

new to java and have a question about getters and setters

new to java and have a question about getters and setters

new to java and have a question about getters and setters

(OP)
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());
}
}

RE: new to java and have a question about getters and setters

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;
} 

RE: new to java and have a question about getters and setters

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".

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close