Search code examples
javaaccess-modifiers

A single Java access modifier for multiple members


I thought I understood pretty much all there was to know about Java's access modifiers until one of my teammates just committed some code with something I've never seen before.

Take a look at the following code while paying attention to the only two access modifiers,

    public class Type {

        private

        int typeID;
        String name;
        String description;

        public

        void setTypeId(int arg)
        {
            typeID=arg;
        }
        int getTypeId()
        {
            return typeID;
        }

        void setName(String arg)
        {
            name=arg;
        }
        String getName()
        {
            return description;
        }

        void setDescription(String arg)
        {
            description=arg;
        }
        String getDescription()
        {
            return description;
        }

    }

My teammate is new to Java but comes from a C++ background which is why I think he set up the private and public access modifiers like that (That's how they're done in header files for C++). But is this valid in Java. I have never seen this syntax before in Java and I cannot find any documentation on it online.

If this is valid does it mean typeID, name, and description are all private and that all the functions under public are in fact public. Or does it mean that only typeID is private and setTypeID is private (since they're the two member declarations under the two access modifiers.


Solution

  • The lack of access modifier indicates package private.

    The single private modifier applies to the typeID field. The single public modifier applies to the setTypeId method.

    Whitespace and indentation is meaningless in Java. (It doesn't matter in C++ either afaik, but in C++ you'd have private:, not just private.)

    Put differently, this

    public class Type {
    
        private
    
        int typeID;
        String name;
        String description;
    

    is the same as

    public class Type {
    
        private int typeID;
        String name;
        String description;
    

    which is the same as

    public class Type { private int typeID; String name; String description; //...