Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By gimbal2

Thread: What is the benefit of making a method private?

  1. #1
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default What is the benefit of making a method private?

    To my understanding, methods can either be private or public. I was told that public methods can be accessed by other classes, and privates can't. Why would anyone ever want to make something private. Why wouldn't they want to leave the option open?

    Thanks

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: What is the benefit of making a method private?

    The private methods are to be used by the class itself, perhaps as utility methods or to accomplish something behind the scenes that is not for public consumption. For a simple example, let's say I had a method which would update an index into a data structure. In that method I need to do some checks and bookkeeping before I update the index. If I provided access to that method to direct instances or even subclasses of the class it could actually break things because the sub class does not know when to use the method or why. In this case, the index could be updated when it shouldn't be and would probably break things.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,365
    Rep Power
    6

    Default Re: What is the benefit of making a method private?

    The same reason for keeping a loaded gun in a locked drawer: so someone who shouldn't be touching it can't touch it.
    MW130 likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. how the private method is calling
    By javastuden in forum Advanced Java
    Replies: 1
    Last Post: 05-03-2013, 10:29 AM
  2. private int method - if statement
    By scottmulla in forum New To Java
    Replies: 2
    Last Post: 03-31-2011, 08:57 AM
  3. More than one input in one private method
    By rice in forum New To Java
    Replies: 0
    Last Post: 10-02-2009, 06:08 AM
  4. cannot call private method from static method
    By jon80 in forum New To Java
    Replies: 3
    Last Post: 05-07-2008, 09:37 AM
  5. Private main method
    By bugger in forum New To Java
    Replies: 1
    Last Post: 12-21-2007, 10:45 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
  •