Skip to content

Class Anatomy

Estimated time to read: 1 minute

Overview

The general form of a class is:

public class classname { 
 type attribute1;
 type attribute2;
 type attributeN;

 type methodname1(parameter-list){
  //body of methodname1
 }

 type methodname2(parameter-list){
  //body of methodname2
 }
}

Classes do not have to follow the exact structured order above.

Attributes can be set nearer to its usage within the code, the same can be done with methods too! Getters and Setters can even precede the declaration of the variable. Most new IDE's will complain about this, but theoretically it is doable 🤫

However, it is good practise that a structure is followed within the code. This structure is defined either by the team working on the project, the individual or company. Make sure to stay consistent and follow the structure that is in place across the project!

Some notes

  • Opening and closing braces are used for encapsulating the entire class. This is known as a class block.
  • Any methods within the class have their own braces, which surround the body of the method. These are known as method blocks.
  • Attributes are, typically, defined inside of the class block but outside all of the method blocks.
  • Indentation is not part of the syntactic structure of Java, it is there to provided increased readability.