The structure of a Java class

The aim of this section is to cover the structure and components of a Java class and those of a Java source code file as well. I will try also to cover the similarities and the differences between them.

The components of a Java source code file are:

  • Comments;
  • The package statement;
  • The import statement(s);
  • The class declaration;
  • The extended class and implemented interface(s);
  • The class variables;
  • The class methods;
  • The class constructors.

The previously list contains only components which are for the Java Certification OCA 7 Programmer I. Other components which can appear in a Java source code file are : enumerations, inner classes, nested interfaced, nested classes and annotations.

In a single source code file you can define either :

  • a single java class;
  • a single java interface;
  • multiple java classes;
  • multiple java interfaces;
  • or, a combination of java classes and interfaces (they can be defined in any order of occurrence).

NOTE : There can be ONLY ONE public class OR interface in a java source code. In such case, the name of the file MUST MATCH with the name of the public java type.

A Java class starts with the class declaration, which is marked by the class keyword. A Java class resides in a .java file, and it contains the following elements :

  • class name (this component is mandatory to have a Java class);
  • the extended class (if the class extends another class);
  • all implemented interfaces (if the class implements any interface);
  • class body (usually formed by comments, fields, methods and constructors). The class body is enclosed within a pair of curly braces (i.e, { });
  • access and non-access modifiers.

Among the Java class(es), a Java file contains the package statement, and import statement(s).

Example of a simplest Java Class
Example of a simplest Java Class

Take away : The class name is the only mandatory component to have a Java class.

Pin this : 
If a java file (.java) defines a public class or a public interface its name should match the name of the class or interface. More, you can have only one public class or interface in a java file.

Definition : A class is a design used to specify the properties and the behavior of an object. The properties of an object are implementing using variables, while the behavior of an object is implemented using methods.

 

Add a Comment

Your email address will not be published.