Classes and Objects

Classes and objects are fundamental concepts of object-oriented programming (OOP). They are used to model real-world entities and their interactions in software development. Here's an overview of classes and objects in Java:

1. Classes:

  • A class is a blueprint or template for creating objects. It defines the structure, behavior, and state of objects that belong to it.

  • Classes in Java are declared using the class keyword followed by the class name.

  • A class can have attributes (also known as fields or instance variables) to represent the object's state and methods to define its behavior.

public class Person {
    // Attributes
    String name;
    int age;
    
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Method
    public void introduce() {
        System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
    }
}

2. Objects:

  • An object is an instance of a class. It is a concrete realization of the class blueprint.

  • Objects have their own unique data (values of attributes) and can perform actions (invoke methods) defined by the class.

  • You create objects in Java using the new keyword followed by the class constructor.

  • Here's how you create objects from the Person class:

public class Main {
    public static void main(String[] args) {
        // Creating objects of the Person class
        Person person1 = new Person("Alice", 25);
        Person person2 = new Person("Bob", 30);
        
        // Calling methods on objects
        person1.introduce();
        person2.introduce();
    }
}

In this example, person1 and person2 are instances of the Person class. They have their own name and age attributes and can call the introduce method.

Classes and objects are foundational concepts in Java, allowing you to create reusable and modular code by modeling real-world entities and their interactions. They help organize and structure your code, making it easier to manage and maintain.

Last updated