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.
You should read more carefully: The Oracle Coding conventions you linked to write in section 3.1.3:
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.