Last modified: January 07, 2024
Components of a Java Class
Since a Java program is a collection of objects that interact with one another, your first goal is to learn how to define the behavior of a single type of object.
In Java, the behavior of an object is determined by its class. A class is defined in a text file named in the format "ClassName.java". A class is like a blueprint for an object. It describes everything needed in order to create the object along with code that defines what the object can do and what properties it has.
A Java file's name must exactly match the name of the class it contains.
For example, if a class is named "HelloWorld",
the Java file must be named as "HelloWorld.java". It cannot be named "somethingelse.java" or "helloworld.java" (even the capitalization has to match).
Every class in Java has four major components:
- Class declaration
- Declares the name of the class and lists any classes it extends (is a subclass of) or interfaces it implements
- Extending a class and implementing interfaces is optional and will be discussed later
- Fields
- Variables that store information about the state of the object or class. Fields can be further split into two categories depending on whether the field stores data about a specific instance of a class (an object) or data about the entire class.
- There are two types of fields:
- Instance Variables store information about a particular instance of a class. Also known as attributes or properties
- Class Variables store information about a whole class. Also known as static fields.
If a field is declared with the static keyword, then it is a class variable, otherwise it is an instance variable
- Methods (also called functions or subroutines)
- Define the behaviors, actions, or sets of instructions an object or class can perform
- Some methods return a value, while others just perform actions.
- Constructors
- Constructors define code that should be executed to set up an object when it is created
- This is where instance variables are initialized and any other set up code is executed
- A class can have multiple constructors
- If no constructors are declared explicitly, then a default constructor is defined that takes no parameters
- Constructors are always named exactly the same as the class
- You must always use the
new
keyword in front of every constructor call. For example: new Rectangle(10, 5)
creates a new Rectangle object initialized with parameters 10 and 5.