US Trends

what is class in java with example

A class in Java is a blueprint or template from which objects are created. It groups related data (fields/variables) and behavior (methods/functions) into a single logical unit.

Quick Scoop: Simple Definition

  • A class defines what an object is and what it can do.
  • An object is a real thing you create from that class (an instance of the class).
  • Think: Class = Plan , Object = Actual thing built from that plan.

Example analogy:
You design a Car blueprint (class).
Every real car made from that blueprint (your red car, your friend’s blue car) is an object of that class.

Basic Syntax of a Class

A minimal Java class looks like this:

java

class ClassName {
    // fields (data / variables)
    // methods (behavior / functions)
}

Key points:

  • class is the keyword to declare a class.
  • ClassName usually starts with a capital letter (convention).
  • Everything inside { } is the body of the class.

Core Example: Person Class

Here’s a very simple class with one field and one method:

java

public class Person {
    // field (data)
    String name;

    // method (behavior)
    void printName() {
        System.out.println(name);
    }
}

What this means:

  • Person is a class.
  • name is a field that stores the person’s name.
  • printName() is a method that prints that name.

To actually use this class, you create an object:

java

public class Main {
    public static void main(String[] args) {
        Person p = new Person();   // create object
        p.name = "Alice";          // set field
        p.printName();             // call method → prints: Alice
    }
}

Another Example: Car Class

java

class Car {
    // fields
    String color;
    int year;

    // constructor
    Car(String color, int year) {
        this.color = color;
        this.year = year;
    }

    // method
    void displayInfo() {
        System.out.println("Car color: " + color + ", Year: " + year);
    }
}

Usage:

java

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car("Red", 2020);
        c1.displayInfo();  // Car color: Red, Year: 2020
    }
}

Key Things to Remember

  • A class can contain:
    • Fields (variables)
    • Methods
    • Constructors
    • Sometimes nested classes, interfaces, etc.
  • A class itself is just a definition; memory is allocated when you create an object with new.
  • Typical workflow:
    1. Define a class.
    2. Create objects (instances) of that class.
    3. Use those objects’ fields and methods.

One-Line Answer

A class in Java is a blueprint that defines the data and behavior of objects, and you create actual objects (instances) from it using the new keyword, for example with a Person or Car class as shown above.