-1
$\begingroup$

Good morning everybody. I would like to know if there is a blueprint I could refer to when creating classes and objects in Java? For instance, I was told for classes. You start VARIABLES DECLARATIONS then CONSTRUCTOR then SETTERS AND GETTERS. What do you guys think. Thank you kindly.

PS I have just starting Java.

$\endgroup$
4
  • 1
    $\begingroup$ I seem to remember things like books - for beginners, Eckel's Thinking in Java might still be a good choice, even on-line tutorials. $\endgroup$
    – greybeard
    Oct 27 '20 at 16:40
  • 1
    $\begingroup$ (While programming is off-topic, you don't start with code. You start with specification and design. The first thing to type for something visible externally is its in-line documentation.) $\endgroup$
    – greybeard
    Oct 27 '20 at 16:44
  • $\begingroup$ You could start with method headers and stubs or UML diagrams or pseudocode to help you plan out your code, and then gradually make it concrete by writing actual Java code. If it's the order in which to organize members - then what you were told sounds like the convention, although there's no hard and fast rule, and people can do things slightly differently (e.g. Fields, then setters/getters, then constructors, then methods) $\endgroup$
    – user
    Oct 27 '20 at 18:22
  • $\begingroup$ Perhaps more appropriate for Code Review, as this is about guidelines for writing code. $\endgroup$ Jan 30 at 10:22
1
$\begingroup$

According to Oracle's Java SE Archives

The proper order of a Java file is:

  1. Beginning documentation
  2. Package and Import Statements
  3. Class and Interface Declarations

Where a class/Interface is arranged as follows:

  1. Class/Interface documentation
  2. Class/Interface statement
  3. Class/Interface implementation comments (if needed)
  4. static variables
  5. Instance variables
  6. Constructors
  7. Methods

Variables within each category are organized by access level (public, protected, no modifier, and then private).

Finally it mentions that methods should be organized by functionality.

see: https://www.oracle.com/java/technologies/javase/codeconventions-fileorganization.html

While this archive is from 1999, in my experience people usually stick to this organization system. The organizational variation mostly comes in how people organize methods.

$\endgroup$
1
  • $\begingroup$ Although the homepage states that the methods should be grouped by functionality, I prefer to group them by access level. Most public methods are often redirections to private ones (maybe just different versions with more or fewer parameters), so I list first, what the public 'world' can access. Only then come the (private) functions with the real functionality $\endgroup$ Jan 29 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.