views:

93

answers:

4

In Java, what's generally the most accepted way to organize a class in terms of the order in which declared data members and methods should be listed in the class file, keeping in mind the following and anything else you can think of for each one:

  • its visibility
  • whether it's a constructor, method, or member
  • if it's a method, does it overload, or override other method(s)?
+4  A: 

I've found that the conventions in Code Conventions for the JavaTM Programming Language to be quite suitable. Chapter 3 answers this question.

Mostly it ignores visibility or whether it is an overloaded function etc.

It is simply in order:

  • Class (static) variables
  • Instance variables
  • Constructor
  • Methods

A more rigorous approach could be taken, but I do not see a strong argument in its favor.

Kris
you can add Inner Classes at the bottom of that list for completeness
fuzzy lollipop
@Kris : Thanks!
Cam
I might be likely to put public methods before private just so that the class's external interface is easier to find, but otherwise this is what I nearly always see. Oh, and public static final (#define style) variables ALWAYS grouped at the top before the other instance variables.
Bill K
+1  A: 

You could follow the recommendation used by the Google project GWT, if you want. It's based on the standard Java code conventions from Sun. It adds some strict rules on ordering, also concerning visibility modifiers etc.:

http://code.google.com/webtoolkit/makinggwtbetter.html#codestyle

Chris Lercher
+2  A: 

There are suggested best practices and the ones Kris mentions are pretty much "the" standard, with Inner Classes at the bottom of that list.
That said, if you are using Intellij IDEA (there is a free Community version) there is a plug-in called Rearranger, that lets you specify all this and enforce it and more importantly refactor existing code to be what you think it should be.

fuzzy lollipop
+1 For mentioning Intellij IDEA's Rearranger.
Andrei Ciobanu
+1  A: 

Eclipse (and, I'm sure, other IDEs) will automatically order declarations (Source -> Sort Members), with options for types and visibility. Overloading and overriding aren't available, at least in Eclipse. So I would say establish a convention that includes type and maybe visibility, but not overload/override status, then configure your team's IDE to impose that convention. Automatable - and automated - standards are much easier for the team to adhere to.

Carl Manaster
Netbeans has Source->Format (just discovered this).
Cam