Classes in Java
If we look at the real world, we can think about
Classes as blueprints from where 'items' are built from.
You can imagine the blueprint of an Airplane, which can be used to create multiple planes. All of these planes will expose/contain the same components and behaviours as detailed in the blueprint that they were created from.
In Object Oriented Programming, a Class is a blueprint and the 'items' that are created from these blueprints are referred to as Objects where each different Object is known to be an
instance of the class.
Using the same analogy as before, if we have a class called
Airplane, we could have several different objects created from this class.
A Class defines two main aspects of the objects, their State and Behavior:
State: This is the data that defines each object.
Airplaneexample, we could say that each
manufacturer: Name of the company that built the plane.
numberOfSeats: Capacity of passengers/crew.
landed: Indicates whether the plane has landed or not (true or false), and,
gearDeployed: Indicates if the plane’s landing gear has been deployed (also a true or false flag)
Behavior: These are the behaviors the object exposes and become the interface that allow other objects to interact with instances of our class.
Airplaneexample, we could say that the plane can:
In this sense, we can think of an
Object as a bundle of state and behavior for an instance of a particular
Based on the blueprint above, we can say for example, that all our
Airplane objects have a
manufacturer associated to them.
Class names and the state inside an object should be nouns. Also, class names should be
|Behaviors should be represented by verbs.|
In Java, we say that the state is stored in
fields and the behavior is exposed as
methods of the object. Both, the
fields and the
members of the class.
It is good practice for the state of the object to be private and not allow direct access from other objects, and only allow interaction via the object’s interface, this is, its
methods. This is known as data encapsulation that will be covered in more detail when we talk about access control in Chapter 5.