Skip to content

Classes and Objects

Classes and Objects in Java

Java is an object-oriented programming (OOP) language, and its core concepts revolve around classes and objects. Let’s break this down:


1. Classes in Java

A class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that the objects created from the class can have.

Key Points:

  • It acts as a container for the data and code that manipulates that data.
  • A class does not consume memory until an object is created.

Syntax of a Class

class ClassName {

    // Fields (attributes or variables)

    int field1;

    String field2;

    // Methods (behaviors)

    void display() {

        System.out.println(“This is a method inside the class.”);

    }

}


2. Objects in Java

An object is an instance of a class. When you create an object, you allocate memory and get access to the fields and methods defined in the class.

Key Points:

  • Objects represent the real-world entities modeled in a program.
  • Each object has a unique identity and state (values of fields).

Syntax of Object Creation

ClassName objectName = new ClassName();


Example of Classes and Objects

// Defining a class

class Car {

    // Fields

    String brand;

    int speed;

    // Method

    void displayDetails() {

        System.out.println(“Brand: ” + brand);

        System.out.println(“Speed: ” + speed + ” km/h”);

    }

}

// Main class

public class Main {

    public static void main(String[] args) {

        // Creating objects

        Car car1 = new Car();

        car1.brand = “Tesla”;

        car1.speed = 200;

        car1.displayDetails();

        Car car2 = new Car();

        car2.brand = “BMW”;

        car2.speed = 250;

        car2.displayDetails();

    }

}

Output:

Brand: Tesla

Speed: 200 km/h

Brand: BMW

Speed: 250 km/h


Features of Classes and Objects in Java

  1. Encapsulation: Classes bundle data (fields) and methods that operate on the data.
  2. Reusability: Classes can be reused to create multiple objects with different states.
  3. Inheritance: Classes can inherit properties and methods from other classes.
  4. Polymorphism: Objects can take on multiple forms based on their class or subclass.
  5. Abstraction: Classes can hide complexity by exposing only relevant features.

Real-World Analogy

  • Class: Blueprint of a house. It defines the structure and design.
  • Object: Actual house built using the blueprint. Each house can have unique properties like paint color, furniture, etc.

This distinction makes Java a robust language for modeling real-world problems using OOP principles.