7. Declarations

7.1. Class Declarations

General syntax of the class declaration is as follows:

<class modifiers> class <class name> <extends clause> <implements clause> // Class header
{ // Class body
<field> declarations
<method> declarations
<nested class> declarations
<nested interface> declarations
<nested enum> declarations
<constructor> declarations
<initializer blocks>
}

Let’s look at each element in the class declaration syntax. Many of the concepts/definitions may not be clear to you now, but we’ll learn about these in detail in coming chapters.

The above class declaration syntax can be divided into

Let’s build a new class CoffeMaker and take a closer look at some of the elements in class header and class body.

Note: extends clause, implements clause and nested declarations are covered in coming chapters.

			package javatutorial;

			/**
			 * Class to understand/identify the following elements in class declaration
			 *     •	Class header
			 *     		o	class modifiers  can be public, private, protected etc
			 *     		o	class the Java keyword
			 *     		o	class name name of the Class
			 *     
			 *     •	Class body
			 *     		o	field declarations  declaration of any fields in a class
			 *     		o	method declarations declaration of any methods in a class
			 *     		o	constructor declarations constructor declarations, if any
			 *     
			 *  @author f5java.com   
			 */
			public class CoffeeMaker {
				// 1. Identify parts of class header
				
				// class modifier is public
				// class is the java keyword
				// class name is CoffeeMaker
				
				// 2. Class body consists of
				
				boolean isCoffeemakerOn; // 2a. Field declarations
				int noOfCups;
				String brandName;
				String statusTracker = "Started making your coffee";
				
				/**
				 * Prints coffee making status
				 */
				public void displayCoffeeMakerStatus(){ // 2b. Method declaration
					System.out.println("Coffee make is on: " + isCoffeemakerOn);
					System.out.println("Number of cups requested: " + noOfCups);
					System.out.println("Your coffee making is " + statusTracker);
				}
				
				// 2c. Constructor declaration
				CoffeeMaker(boolean machineSwitch, int requestedQty, String brand){ 
					this.isCoffeemakerOn = machineSwitch;
					this.brandName = brand;
					this.noOfCups = requestedQty;
				}

				public static void main(String[] args) {
					// Instantiate and call the method
					CoffeeMaker myCoffee = new CoffeeMaker(true, 2, "StarBucks");
					myCoffee.displayCoffeeMakerStatus();

				}

			}