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?
Class Modifiers and Member Modifiers
Collapse
X
-
Tags: None
-
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.Originally posted by devgupta01I 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? -
Rule of thumb for a new programmer:
Data is private within a class, methods are public.
If we have the class Thing, for instance:
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...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; } }
Creating these kinds of accessor (get data) methods and mutator (change data) methods is usually considered good practice...
Until again,
TomComment
Comment