Search code examples
javaconventions

Does a convention about the structure of a class exist?


When I write a class in Java, it (almost) always looks like this:

public class MyClass {

    // attributes

    // constructors

    // methods:
    //   * "interesting" methods
    //   * getters and setters
    //   * toString / equals / hashCode
}

Especially, I always write all attributes at the beginning.

Is there a convention how to structure classes in Java?

I couldn't find it in the Oracle Code Conventions. I am interested in sources (e.g. other style guides like Mozilla Coding Style or books), because I am a Java tutor and I would like to give my students more than "I have learned it that way so you should also do it like this". And if there are reasons / sources that propose other structures within a class, I'd also be happy to know that.

edit: Although I am interested in your thoughts, I think I should stress that I expect sources. Personal experience is interesting, but I also made the experience that the structure above is common. But I want to give my students something more than the vague impression, that everybody seems to use this structure. Especially, as some of them don't use it.


Solution

  • You should read more carefully: The Oracle Coding conventions you linked to write in section 3.1.3:

    The following table describes the parts of a class or interface declaration, in the order that they should appear. See “Java Source File Example” on page 19 for an example that includes comments.

    1. Class/interface documentation comment (/**...*/)

      See “Documentation Comments” on page 9 for information on what should be in this comment.

    2. class or interface statement

    3. Class/interface implementation comment (/*...*/), if necessary

      This comment should contain any class-wide or interface-wide information that wasn’t appropriate for the class/interface documentation comment.

    4. Class (static) variables

      First the public class variables, then the protected, and then the private.

    5. Instance variables

      First public, then protected, and then private.

    6. Constructors

    7. Methods

      These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.

    That said, this convention is quite dated, and the fine print usually not followed. For instance, it seems weird to order fields by accessiblity, but methods by functionality. Indeed, I rarely see fields ordered by accessiblity in professional code. The ordering of the bullet points is adhered to quite universally in professional code, though.