Home » Java Tutorial » Java Classes and Objects – A Complete Guide for Beginners

Java Classes and Objects – A Complete Guide for Beginners

Imagine you’re trying to design a blueprint for building cars. The blueprint itself doesn’t create a car but defines what a car should have – wheels, engine, color, etc. Once the blueprint is ready, you can use it to create many cars, each with their own color, engine type, and so on.

This is exactly how Classes and Objects work in Java.

  • A Class is the blueprint.
  • An Object is the real-world instance of that blueprint.

Java is an Object-Oriented Programming (OOP) language. Everything in Java revolves around creating classes and objects.

What is a Class?

A Class in Java is a user-defined data type that acts as a template to create objects. It defines properties (fields) and behaviors (methods).

A Class in Java is like a blueprint or template. It is used to create objects.

Think of a Car as a concept:

  • Every car has properties like color, model, speed.
  • Every car can perform actions like start, stop, accelerate.

You can create many cars (objects) from this single concept (class).

Class = Data + Behavior

A class defines:

  1. Fields – also called attributes or variables (to store data).
  2. Methods – to define behavior or actions the object can perform.

Syntax of a Class

class ClassName {
    // Fields (attributes or variables)
    dataType variableName;

    // Methods (behaviors)
    returnType methodName() {
        // method body
    }
}

Example with Explanation

class Student {
    // Fields
    String name;
    int age;

    // Method
    void study() {
        System.out.println(name + " is studying.");
    }
}

What’s happening here?

  • Student is a class.
  • name and age are variables storing data.
  • study() is a method that prints what the student is doing.

Now let’s create an object of this class.

What is an Object?

An Object is a real-world entity created from a class. It holds its own values for the variables defined in the class.

Definition (Simple):

An object is a real-world entity that has:

  • State (data/fields/attributes)
  • Behavior (methods/functions)

You create an object from a class and then assign values and call methods using it.

Syntax to Create an Object:

ClassName objectName = new ClassName();

This means:

  • ClassName = the name of your class (like Car, Student, etc.)
  • objectName = name you want to give your object (like myCar)
  • new = Java keyword to allocate memory
  • ClassName() = calls the constructor to create the object

Real Example (Explained Step by Step):

Let’s say you already have a class:

class Car {
    // Fields
    String color;
    int speed;

    // Method
    void drive() {
        System.out.println("Car is driving at " + speed + " km/hr.");
    }
}

Now let’s create and use an object:

public class Main {
    public static void main(String[] args) {
        // Step 1: Create object of Car
        Car myCar = new Car();

        // Step 2: Assign values to fields
        myCar.color = "Red";
        myCar.speed = 100;

        // Step 3: Call method
        myCar.drive();  // Output: Car is driving at 100 km/hr.
    }
}

Explanation of Each Step:

Step 1: Creating the object

Car myCar = new Car();
  • Car → class name
  • myCar → object name
  • new Car() → creates a new object of Car class in memory

Step 2: Assigning values

myCar.color = "Red";
myCar.speed = 100;
  • These set the object’s own values
  • If you create another car, you can assign it different values

Step 3: Calling a method

myCar.drive();
  • This calls the drive() method of the myCar object
  • Output depends on the speed value

Components of a Class

Let’s break down a class into parts:

Fields (Attributes)

These are variables that store data/state of the object.

String name;
int age;

Methods

These define the behavior of the object.

void bark() {
    System.out.println("Woof! Woof!");
}

Constructors

A constructor is a special method that runs when you create an object using new. It initializes the object.

class Dog {
    String name;

    // Constructor
    Dog(String n) {
        name = n;
    }
}

Real Life Analogy

ClassObject
BlueprintActual building
RecipeCooked dish
Car classMaruti, BMW, Honda cars
Dog classBruno, Tommy, Sheru

Types of Classes in Java

1. Regular Class (as above)

A regular class is the most common type. It can have:

  • Fields
  • Methods (complete)
  • Constructors

You can create objects from this class.

Example

class Animal {
    String name;

    void makeSound() {
        System.out.println(name + " is making a sound");
    }
}

2. Abstract Class – Contains abstract (incomplete) methods.

An abstract class is like an incomplete class. It cannot be instantiated directly (i.e., you can’t create its object).
It may contain:

  • Abstract methods (methods without a body)
  • Concrete methods (with body)

You must extend it and implement its abstract methods in a subclass.

Example

abstract class Shape {
    abstract void draw(); // abstract method
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing Circle");
    }
}

Use Case:

Useful when you want to define a base structure and enforce subclasses to implement certain methods.

3. Final Class – Cannot be extended.

A final class cannot be inherited (extended). No other class can subclass it.

Example

final class Constants {
    static final double PI = 3.14159;
}

Use Case:

Use it when you want to prevent modification or extension, such as for security or utility classes.

4. Anonymous Class – No name, used for quick method override.

An anonymous class has no name.
It is created on the fly—usually for quick implementation of interfaces or abstract classes.

Example

abstract class Animal {
    abstract void sound();
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Animal() {
            void sound() {
                System.out.println("Dog barks");
            }
        };
        dog.sound(); // Output: Dog barks
    }
}

Use Case:

Used when you need to override a method quickly without creating a new named class.

5. Nested Class – Class inside another class.

A nested class is a class declared inside another class.

Types of Nested Classes:

  1. Static Nested Class – Can be accessed without creating an outer object.
  2. Non-static Inner Class – Requires outer class object to access.
  3. Local Class – Defined inside a method.
  4. Anonymous Inner Class – No name; used for short overrides.

Example

class Outer {
    int x = 10;

    class Inner {
        void show() {
            System.out.println("x = " + x);
        }
    }
}

6. POJO Class – Plain Old Java Object, used to hold data.

A POJO is a simple Java class used to hold data.
It follows certain rules:

  • No business logic
  • Has private fields
  • Public getter/setter methods
  • No-argument constructor (usually)

Example

public class Student {
    private String name;
    private int age;

    public Student() {}

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

Use Case:

Used in Java Beans, REST APIs, and frameworks like Hibernate to transfer or hold data.

Benefits of Using Classes and Objects

  • 📦 Modular Code: Easy to understand and maintain.
  • 🔁 Reusability: Classes can be reused to create multiple objects.
  • 🔐 Encapsulation: Data hiding using access modifiers.
  • 🔗 Real-world Mapping: Easy to relate to real-life entities.

Practice Programs

Q1: Create a class Person with fields name and age. Write a method sayHello() that prints “Hello, I am [name] and I am [age] years old.”

class Person {
    String name;
    int age;

    void sayHello() {
        System.out.println("Hello, I am " + name + " and I am " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.name = "Rahul";
        p1.age = 24;
        p1.sayHello();
    }
}

Q2: Create a class Rectangle with fields length and breadth. Write a method area() to print the area.

Quiz Time

1. What is the purpose of a class in Java?
a) To define variables only
b) To store runtime values
c) To act as a blueprint for objects ✅
d) To write the main method

2. What is the correct way to create an object of class Animal?
a) Animal a = Animal();
b) Animal a = new Animal(); ✅
c) a = new Animal();
d) Animal = new a();

3. Which of these is NOT a part of a class?
a) Constructor
b) Method
c) Object ✅
d) Field

Summary

  • A Class is like a blueprint that defines properties and behaviors.
  • An Object is a real instance of a class.
  • Classes can contain fields, methods, and constructors.
  • Objects are created using the new keyword.
  • Java’s OOP power comes from organizing code using classes and objects.

Final Words

Once you understand classes and objects, you unlock the real power of Java. Everything you build – from simple programs to full enterprise apps – will revolve around this concept. Practice well and try creating your own classes representing real-world things like BankAccount, Mobile, Employee, and more.