Results 1 to 4 of 4
  1. #1
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default Private variable manipulation with set / get methods (should be easy)

    Okay, so, let's assume that I have a variable called num which is declared as such:

    Java Code:
    public class number{
        private int num;
    and I have this code for my get / set methods:

    Get:
    Java Code:
    public int getNum(){
         return num;
     } // End get Num
    Set:
    Java Code:
     public void setNum(int x){
         x = numBoats;
    }

    Main calls this with the following code:

    Java Code:
    int x=4;
    number.setNum(x);
    What would I need to do to call this from main? At present I can't call the non-static method from main (which makes sense since main is static) I just can't seem to get around this with my current knowledge.

  2. #2
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    620
    Rep Power
    4

    Default

    Hi
    You just make a new instance by Number class like as
    Java Code:
    Number number = new Number();
    number.setNum(4);
    Skype: petrarsentev
    http://TrackStudio.com

  3. #3
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    Quote Originally Posted by Petr View Post
    Hi
    You just make a new instance by Number class like as
    Java Code:
    Number number = new Number();
    number.setNum(4);

    Many thanks, that was quick and easy.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    Your setNum is wrong. You assign the value of the parameter x to some unknown field numBoats and do nothing else with it. Why?

    Also note:
    -- by convention, Java class names begin with an Uppercase Letter (variable and method names begin with a lowercase letter, with the exception of final static constants, which are ALL_UPPERCASE)

    -- Do not name any custom class the same as a class in the java.lang package. That way lies grief.

    db

Similar Threads

  1. Multiple private methods
    By java4deepak in forum New To Java
    Replies: 4
    Last Post: 01-05-2011, 02:05 PM
  2. Replies: 17
    Last Post: 10-14-2010, 11:26 PM
  3. Replies: 5
    Last Post: 10-11-2010, 02:16 AM
  4. Replies: 1
    Last Post: 12-09-2009, 01:57 AM
  5. same object variable t and same methods is calling
    By javastuden in forum New To Java
    Replies: 1
    Last Post: 11-24-2009, 05:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •