Understanding Java Classes and Objects

In Java, a class is a blueprint for creating objects. Objects are instances of a class, and they encapsulate data and behavior. Let's explore how classes and objects are defined and used in Java.

Defining a Class:

A class in Java is defined using the class keyword. It contains fields (variables) and methods (functions).


// Define a simple class named 'Car'
public class Car {
  // Fields (variables)
  String brand;
  int year;
  
  // Methods (functions)
  void startEngine() {
    System.out.println("Engine started");
  }
  
  void drive() {
    System.out.println("Car is moving");
  }
}

Creating Objects:

Objects are created from a class using the new keyword. Each object is an instance of the class and has its own set of data and can invoke the methods defined in the class.


// Create objects of the 'Car' class
Car myCar = new Car();
Car anotherCar = new Car();

// Set values for the fields
myCar.brand = "Toyota";
myCar.year = 2022;

anotherCar.brand = "Honda";
anotherCar.year = 2021;

// Invoke methods on objects
myCar.startEngine();
anotherCar.drive();

Example:

Here's an example demonstrating the use of classes and objects in Java:


// Define a class named 'Person'
public class Person {
  // Fields
  String name;
  int age;

  // Method to display information
  void displayInfo() {
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
  }
}

// Create objects of the 'Person' class
Person person1 = new Person();
Person person2 = new Person();

// Set values for the fields
person1.name = "John";
person1.age = 25;

person2.name = "Alice";
person2.age = 30;

// Display information using methods
person1.displayInfo();
person2.displayInfo();

Note:

Classes and objects are fundamental concepts in object-oriented programming (OOP). Classes define the structure and behavior, and objects represent instances of those classes. They enable you to model and organize code in a modular way.