Class Modifiers and Member Modifiers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • devgupta01
    New Member
    • Jan 2008
    • 20

    Class Modifiers and Member Modifiers

    I have seen the class with public and without modifiers and method with public, protected or private modifiers. I am confused how to decide modifiers for a class?
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    Originally posted by devgupta01
    I have seen the class with public and without modifiers and method with public, protected or private modifiers. I am confused how to decide modifiers for a class?
    The choice of modifier, whether it be for a top-level class or interface, a class member or a constructor, always comes does to the same question: how visible should this thing be? The answer to that question can only come from the context of your problem, not from an answer in a forum, but a general rule of thumb is to give as restrictive access as you can: give top-level class's default access and class members and constructors private access. As you develop you will find some of this is too restrictive -- then you think about making access wider. This is easier to do that making access too easy then realizing much alter that was a mistake.

    Comment

    • tburger
      New Member
      • Jul 2007
      • 58

      #3
      Rule of thumb for a new programmer:

      Data is private within a class, methods are public.

      If we have the class Thing, for instance:

      Code:
      public class Thing{
          // private data
          private String name;
          private int age;
      
         // public accessor methods
        public String getName(){
            return name;
        }
      
        public int getAge(){
            return age;
        }
      
        // public mutator methods
      
        public void setName(String n){
            name = n;
        }
      
        public void setAge(int a){
           age = a;
        }
      
      }
      In most of your typical introductory work in Java, creating classes in this way will allow you to make your classes public 99% time. As stated above, however, more advanced programming (requiring inheritance and interface classes) will cause you to start recognizing more effective ways of declaring things public or private...

      Creating these kinds of accessor (get data) methods and mutator (change data) methods is usually considered good practice...

      Until again,

      Tom

      Comment

      Working...