The majority of objects are created using the concept of encapsulation. Encapsulation is the process of creating a class that combines the data and methods of an object together. Java provides a mechanism for safeguarding the internals of an object from the outside world. i.e. other objects.
Good encapsulation will only allow the members of an object (the internal data) to be changed via the methods defined within the object. These methods provide the programmer with a way of communicating with the object. Objects may communicate with other objects only through these methods, thus providing protection of the data from external influences.
A class is a template that defines an object. Using a library system as an example, there would be many books, each having states and behaviours that, collectively, make them part of the class of Books. Each book in the library is created from one single set of design plans or blueprints.
Only one set of blueprints is needed for each type of book. From the blueprints an infinite number of book objects can be created. To create a new set of blueprints for each new book, when they all share the same attributes, is both inefficient and time-consuming.
OOP takes this principle on board by enabling the class definition for the book to be reused, rather than having to create a new definition each time.
A class is a blueprint (or a prototype) that defines the data and methods common to all objects of a certain kind. Each object that is created is known as an instance of the class. Every time an object is instantiated (i.e. an instance of the class is created) it will have its own set of members. It is important to note that instances of the same class (i.e. objects) share the same method implementations, i.e. the methods are not duplicated for each object of the class. It will appear that each object has its own set of methods.
Classes provide the programmer with the benefits of software reusability. Software programmers can use the same class over and over again in different software applications.
The following shows the general syntax for creating instances of classes: