Eugene
Eugene

Reputation: 60184

Convention for methods declaration in Java

Is there a convention in Java on where to declare fields - before or after methods?

Upvotes: 5

Views: 3741

Answers (7)

Nishant
Nishant

Reputation: 55866

Class layout: see here http://java.sun.com/docs/codeconv/html/CodeConventions.doc2.html#1852

The following table describes the parts of a class or interface declaration, in the order that they should appear

  1. Class/interface documentation comment (/*.../)
  2. class or interface statement
  3. Class/interface implementation comment (/.../), if necessary
  4. Class (static) variables
  5. Instance variables
  6. Constructors
  7. Methods

Upvotes: 6

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

According to Sun's "Code Conventions for the Java Programming language", this is indeed the case: static fields first, then instance fields, then constructors, then methods.

However this part of the conventions is not quite as widely confirmed to as others: while using non-capitalized class names or capitalized variable names will immediately yield protests from the vast majority of Java programmers, many will accept putting fields next to the methods that operate on them.

Upvotes: 0

yan
yan

Reputation: 20982

From most code I've seen, fields get declared before methods. This isn't set in stone, as some people follow the common C++ practice of putting public fields and methods first, and then private fields and methods. I wouldn't treat it as a strict guideline; just ask yourself what makes your code more understandable by another person.

Upvotes: 0

david van brink
david van brink

Reputation: 3642

I've mostly seen them at the top. One engineer I respect puts them at the bottom (to emphasize that you shouldnt be thinking about them :). You can avoid the Thinking About problem entirely by coding to interface, not classes. Also, take your vitamins. And floss!

Upvotes: 0

Haphazard
Haphazard

Reputation: 10948

Fields before methods is the most common style.

Upvotes: 0

miku
miku

Reputation: 188024

Most of the code I saw declared fields first, then methods (which is also suggested by the Java code conventions guide: http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852)

Upvotes: 2

Related Questions