Classes and Objects

Thinking

Object-Oriented Programming is the backbone of Java, and understanding classes and objects is essential for building scalable and maintainable software.

By modeling real-world entities as classes and objects, Java allows developers to create modular programs that are easy to understand, debug, and reuse.

Description

In Java, a class is a blueprint for creating objects. It defines the structure and behavior (data members and methods) of the objects.

An object is an instance of a class. When a class is instantiated using the new keyword, an object is created in memory with its own copy of the class’s attributes and methods.

  • Classes contain fields (variables) and methods (functions).
  • Objects access class members using the dot (.) operator.
  • Multiple objects can be created from a single class, each with its own state.

Video Resources

Java Classes and Objects

Learn the basics of class and object creation in Java with examples.

Examples (code)

Basic Class and Object Example


class Car {
    String color;
    int speed;

    void drive() {
        System.out.println("The car is driving at " + speed + " km/h.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.color = "Red";
        myCar.speed = 120;
        myCar.drive();
    }
}
  

Multiple Objects from Same Class


class Student {
    String name;
    int age;

    void showDetails() {
        System.out.println(name + " is " + age + " years old.");
    }
}

public class School {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Alice";
        s1.age = 20;
        s1.showDetails();

        Student s2 = new Student();
        s2.name = "Bob";
        s2.age = 22;
        s2.showDetails();
    }
}
  

Real-World Applications

Vehicle Systems

Represent vehicles like cars, bikes, and buses as objects with behavior and state.

Student Management

Create objects for students, teachers, and classes in education systems.

Healthcare Systems

Patients, doctors, appointments are modeled as objects for hospital management.

Interview Questions

Q1: What is the difference between a class and an object?

Show Answer

A class is a blueprint or template, while an object is an instance of that class.

Q2: How are objects created in Java?

Show Answer

Objects are created using the new keyword, which allocates memory for the object.

Q3: Can we have multiple objects from the same class?

Show Answer

Yes, multiple objects can be created from the same class, each with its own state and behavior.