Class and Objects

In Java, the concept of classes and objects forms the foundation of Object-Oriented Programming (OOP). These concepts help in modeling real-world entities and organizing code in a logical, maintainable, and reusable way.

Class

A class in Java can be thought of as a blueprint or template for creating objects. It defines the properties and behaviors that the objects created from the class will have. In simpler terms, a class is like a blueprint for a house, while the objects are the actual houses built from that blueprint.

A class can have:

  • Fields (Variables): These are the attributes or properties that represent the state of the object.
  • Methods: These are the actions or behaviors that an object can perform.
  • Constructors: Special methods used for initializing objects.
  • Access Modifiers: These define the visibility or scope of classes, methods, and variables.

Syntax

In the above example:

  • The class Car defines three properties: make, model, and year.
  • It has a constructor that initializes these properties when an object is created.
  • It also defines a method called displayCarInfo that prints out the car’s details.

Object

An object in Java is an instance of a class. When a class is defined, no memory is allocated until an object is created. Objects are created using the new keyword, and they hold specific values for the fields defined in the class.

In the above example, an object of the Car class would be an actual car, such as a “Toyota Corolla 2020”.

Syntax

To create an object from a class, you use the new keyword followed by the constructor of the class:

In this case, myCar is an object of the Car class, and we call the displayCarInfo() method to print out its details.

Example

Output

In this example:

  • The class (Book) is the template that defines the properties and behaviors of books.
  • The objects (book1, book2, book3) are instances of the Book class, each representing a specific book with its unique data.
  • Methods like displayBookInfo() act on these objects, performing actions based on their data.

Differences Between Classes and Objects

Aspect Class Object
Definition Blueprint or template for creating objects Instance or concrete representation of a class
Memory No memory is allocated Memory is allocated when created
Creation Defined using the class keyword Created using the new keyword
Purpose Defines properties and behaviors Represents real-world entities with specific values