Having a good understand about structure of a Java class is important to write proper, efficient and clean code. Though you can read about class declarations in the Java Language Specification (JLS), it’s quite formal and specific to language designers. So in this Java core article, I’d like to share with you easy-to-understand structure of a Java class with various real life code examples.

Table of Content:

1. Complete structure of a Java class

2. Class modifiers

3. Class name

4. Extending a super class

5. Implementing super interfaces

6. Field Declarations

7. Static Initializers

8. Instance Initializers

9. Constructors

10. Method Declarations

 

1. Complete structure of a Java class

The complete structure of a Java class is as follows:

<class modifiers> class className extends <super_class> implements <super_interface> { 
     Field Declarations
     Static Initializers
     Instance Initializers
     Constructors
     Method Declarations
}
Below is an example class that follows the above syntax. No worries if you don’t understand, as I’ll explain further below.

public class RoundedCornerSquare extends Square implements Shape {

	/** Field Declarations: **/
	private static double cornerRadius;
	private String fillColor;
	private String borderColor;


	/** Static Initializers: **/
	static {
		cornerRadius = 1.58;
	}

	/** Instance Initializers: **/
	{
		fillColor = "White";
		borderColor = "Black";
	}

	/** Constructors: **/
	public RoundedCornerSquare() {
		this.width = 15;
	}

	public RoundedCornerSquare(int width) {
		this.width = width;
	}

	public RoundedCornerSquare(int width, String fillColor) {
		this.width = width;
		this.fillColor = fillColor;
	}

	/** Method Declarations: **/
	public double calculateArea() {
		return width * width;
	}

	public double calculatePerimeter() {
		return width * 4;
	}

	public void printDetails() {
		System.out.print("Rounded Corner Square[width=" + width);
		System.out.print(", radius=" + cornerRadius);
		System.out.print(", fillColor=" + fillColor);
		System.out.println(", borderColor=" + borderColor + "]");
	}

	public static void main(String[] args) {
		RoundedCornerSquare square1 = new RoundedCornerSquare();
		RoundedCornerSquare square2 = new RoundedCornerSquare(20, "Blue");

		square1.printDetails();
		square2.printDetails();
	}
}
Code of the Shape interface:

public interface Shape {

	double calculateArea();

	double calculatePerimeter();

}
Code of the Square class:

public class Square {

	protected int width;

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}
}
Let me explain each part of the class structure in detailed.


2. Class modifiers

A class should be preceded by one or more modifiers that specify its visibility (public, protected, private, sealed) or characteristics (abstract, static, final, strictfp).



A class can be top level class which is independent or member class which is directly inside another class (nested). The modifiers protected, private and static apply for only member classes. The modifier public can be used for any kind of classes.

A public class is accessible anywhere. The above Square and RoundedCornerSquare are examples of top-level public classes.

A private member class is accessible only within the enclosing class. For example:

public class EnclosingClass {

	private class MemberClass {
	}

	public void test() {
		MemberClass m = new MemberClass();
	}
}
A protected member class is accessible in the enclosing class and different classes in the same package. Below is an example:

public class EnclosingClass {

	protected class MemberClass {
	}
}
An abstract class means that it is incomplete with abstract methods that has no body (no concrete code). And non-abstract subclasses must provide implementation for the abstract methods. Below is an example:

public abstract class Animal {

	public void eat() {
		System.out.println("Eating..");
	}

	public abstract void move();
}

public class Bird extends Animal {
	public void move() {
		System.out.println("Flying...");
	}
}
You can declare a static class inside another class. Read this article for more details.

A final class cannot be extended. Check this article to learn more about final class.

And read this article to understand about using strictfp modifier.

Recent Java versions allow you to declare a sealed class which specifies exactly its known subtypes. For example:

public sealed class Shape permits Rectangle, Circle, Triangle { }
Here, the Shape class permits exactly only 3 subclasses that are Rectangle, Circle and Triangle. These subclasses are known at compile time, and no other classes can extend the Shape class.


3. Class name

The name of a class should follow general naming for identifiers in Java. It should start with an upper case letter. It should not contain special characters ($, _, -, @...). If class name is compound words, the first letter of each word should be capitalized (camel case naming).

You should spend time to name a class in way that it is descriptive and meaningful - the name reveals the intention/purpose of the class properly. It should not an ambiguous name.

Some examples of bad class names: 1StudentManager, square2, Paint_Canvas, applicationcontext,…

Some examples of good class names: StudentManager, Square, PaintCanvas, ApplicationContext,..


4. Extending a super class

A class can inherit public and protected members from another class via the extends keyword. In the above example, the RoundedCornerSquare class extends the Square class:

public class RoundedCornerSquare extends Square {
}
public class Square {

	protected int width;

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}
}
This means RoundedCornerSquare is a subtype of Square and it inherits the member variable width and methods getWidth() and setWidth().

Note that a class can extend only one direct superclass. Read this article to learn more about inheritance in Java.


5. Implementing super interfaces

A class can be a subtype of one or more interfaces via the implements keyword. In the precede code example, you can see the RoundedCornerSquare class implements the Shape interface:

public class RoundedCornerSquare extends Square implements Shape {
}
Below is another example:

public class SUV extends Car implements Vehicle, Moveable {
}
The class SUV implements two interfaces Vehicle and Moveable so it must override methods declared in those interfaces.

Learn more: 12 Rules and Examples About Inheritance in Java


6. Field Declarations

In Object-Oriented Programming (OOP), fields represent characteristics of a class. You declare fields or member variables at the beginning of the class’ body. As you can see in the above code example:

public class RoundedCornerSquare extends Square implements Shape {

	private static double cornerRadius;
	
	private String fillColor;
	private String borderColor;

}
Here, this class has 3 fields. The first one is a static field (cornerRadius) and the last twos are instance fields. Read my explanation in this article to understand static vs. non-static stuffs in Java.

You can declare any number of fields in a class and in any order. However, it’s a good practice to declare fields at the beginning of the class for readability.


7. Static Initializers

If you want a piece of code to be executed only once when the class is first loaded, regardless the number of instances of the class created, you can use static initializers. As you can see in the above example, the RoundedCornerSquare class has one static initializer (the code inside static { } block):

public class RoundedCornerSquare extends Square implements Shape {

	private static double cornerRadius;
	
	static {
		cornerRadius = 1.58;
	}
	
}
In a Java class, you can put any number of static initializers and they are executed in the order specified in the class. Learn more: Java default Initialization of Instance Variables and Initialization Blocks


8. Instance Initializers

If you want a piece of code to be executed whenever a new instance of a class is created, you can use instance initializers. Below is an example:

public class RoundedCornerSquare {

	private String fillColor;
	private String borderColor;

	{
		fillColor = "White";
		borderColor = "Black";
	}
	
}
An instance initializer is the code between { } block. You can put any number of instance initializers in a class, and they are executed in the order they appear in the class.

Read this article to learn more about initialization blocks.


9. Constructors

The next part in a Java class is constructors. A constructor is a special method that is executed when a new object (instance) of the class is created using that constructor (it has same name as the class name). Let’s see an example:

public class RoundedCornerSquare extends Square implements Shape {

	private static double cornerRadius;
	private String fillColor;
	private String borderColor;

	public RoundedCornerSquare() {
		this.width = 15;
	}

	public RoundedCornerSquare(int width) {
		this.width = width;
	}

	public RoundedCornerSquare(int width, String fillColor) {
		this.width = width;
		this.fillColor = fillColor;
	}

}
You can see this class has 3 constructors, with each has different number of parameters.

Learn more: 9 Rules about Constructors in Java


10. Method Declarations

After constructors, you declare methods. A method implements a specific behavior of a class. In the precede example, the RoundedCornerSquare class implements 4 methods:

public class RoundedCornerSquare extends Square implements Shape {

	public double calculateArea() {
		return width * width;
	}

	public double calculatePerimeter() {
		return width * 4;
	}

	public void printDetails() {
		System.out.print("Rounded Corner Square[width=" + width);
		System.out.print(", radius=" + cornerRadius);
		System.out.print(", fillColor=" + fillColor);
		System.out.println(", borderColor=" + borderColor + "]");
	}

	public static void main(String[] args) {
		RoundedCornerSquare square1 = new RoundedCornerSquare();
		RoundedCornerSquare square2 = new RoundedCornerSquare(20, "Blue");

		square1.printDetails();
		square2.printDetails();
	}
}
A method can be static or non-static. You can declare any number of methods in any order in the class. However, it’s a good practice to keep the number of methods and the method body as small as possible.

So far, you have learned details about structure of a Java class with code examples. I recommend you read the following articles to learn more.

Watch the following video to see the coding in action:

 

Further Reading:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment