Chapter 1 - Java for Beginners Course

Classes And Objects

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:

  1. State: This is the data that defines each object.
    In our Airplane example, we could say that each Airplane has a:

    1. manufacturer: Name of the company that built the plane.

    2. numberOfSeats: Capacity of passengers/crew.

    3. landed: Indicates whether the plane has landed or not (true or false), and,

    4. gearDeployed: Indicates if the plane’s landing gear has been deployed (also a true or false flag)

    5. etc.

  2. Behavior: These are the behaviors the object exposes and become the interface that allow other objects to interact with instances of our class.
    In our Airplane example, we could say that the plane can:

    1. takeOff

    2. land

    3. deployLandingGear

    4. retractLandingGear

    5. etc.

In this sense, we can think of an Object as a bundle of state and behavior for an instance of a particular Class.

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 PascalCased, for example, Airplane instead of airplane, and CommercialAirplane instead of commercialAirplane.
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 methods are 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.