Java Classes/Objects


In Java, everything revolves around classes and objects. They are the foundation of Object-Oriented Programming (OOP). A class defines what an object is, and an object represents a real-world entity created from that class. If you understand this relationship clearly, you can design any Java program in a structured and reusable way.

In this tutorial, you’ll learn what classes and objects are, how to define them, how to create objects, how memory works, and how to use them in real examples.

What is a Class in Java?

A class in Java is a blueprint or template used to create objects. It defines the attributes (variables) and behaviors (methods) that the objects of that class will have.

For example, think of a class as a blueprint of a house. The blueprint itself isn’t a house, but it describes what the house will look like and how it will be built. You can use the same blueprint to build many houses. Similarly, a class can be used to create multiple objects.

The basic structure of a class looks like this:

class ClassName {
    // Fields (Attributes)
    // Methods (Behavior)
}

Here:

  • Fields store data.

  • Methods define actions.

Example of a Simple Class

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

    // Method
    void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

In the above example, Student is a class that has two attributes (name and age) and one method (displayInfo()).

What is an Object in Java?

An object is an instance of a class. When you create an object, memory is allocated to hold the data defined by the class.

For example, if a class is a blueprint, then an object is the actual product built using that blueprint.

You create an object in Java using the new keyword:

Student s1 = new Student();

Here:

  • Student is the class name.

  • s1 is the reference variable (object name).

  • new Student() creates a new object in memory.

You can then assign values to its attributes and call its methods.

Example: Creating and Using Objects

class Student {
    String name;
    int age;

    void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        Student s1 = new Student();  // Object 1
        s1.name = "Riya";
        s1.age = 20;

        Student s2 = new Student();  // Object 2
        s2.name = "Tina";
        s2.age = 22;

        s1.displayInfo();
        s2.displayInfo();
    }
}

Output:

Name: Riya
Age: 20
Name: Tina
Age: 22

Here, both s1 and s2 are objects of the Student class, each storing its own set of data. This demonstrates how objects are independent copies of a class blueprint.

Memory Representation of Objects

When an object is created using new, Java allocates memory in the heap area for that object.
The reference variable (like s1) stores the address of the memory location. Even if multiple objects are created from the same class, each object gets its own separate memory.

For instance, in the above example:

  • s1 → has name “Riya” and age 20.

  • s2 → has name “Tina” and age 22.

Changing data in one object does not affect another.

Multiple Objects of a Single Class

You can create as many objects of a class as needed. Each object holds its own values, even though they are defined using the same class.

Example:

Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();

All three are different objects that share the same class structure but store different data.

Accessing Class Members

Class members include variables (attributes) and methods (functions).
You can access them using the dot operator (.) with the object name.

Example:

s1.name = "Anita";
s1.displayInfo();

The dot operator connects the object to its class members.

Real-Life Example: Class and Object

Let’s take a real-world example of a Car.

class Car {
    String brand;
    int speed;

    void start() {
        System.out.println(brand + " is starting...");
    }

    void accelerate() {
        System.out.println(brand + " is accelerating at " + speed + " km/h.");
    }

    public static void main(String[] args) {
        Car c1 = new Car();
        c1.brand = "Honda";
        c1.speed = 120;

        Car c2 = new Car();
        c2.brand = "BMW";
        c2.speed = 200;

        c1.start();
        c1.accelerate();

        c2.start();
        c2.accelerate();
    }
}

Output:

Honda is starting...
Honda is accelerating at 120 km/h.
BMW is starting...
BMW is accelerating at 200 km/h.

Each car (object) acts independently but follows the same structure defined by the Car class.

Anonymous Objects

In Java, you can also create an object without assigning it to a variable.
These are called anonymous objects.

Example:

new Car().start();

Anonymous objects are useful when you only need to use the object once, such as for calling a method.

Class and Object Relationship

Here’s how they relate:

  • A class defines the structure (like a model).

  • An object is an instance of that structure (like an actual item).

  • You can create many objects from one class.

  • Every object has its own copy of instance variables but shares the same methods.

Types of Classes in Java

  1. Concrete Class: A regular class that can be instantiated (like Student, Car).

  2. Abstract Class: A class that cannot be instantiated directly and may contain abstract methods.

  3. Final Class: A class that cannot be extended.

  4. Nested/Inner Class: A class defined inside another class.

For now, focus on concrete classes. The others will make more sense when you learn about abstraction, inheritance, and modifiers later.

Key Points to Remember

  • A class is a blueprint, and an object is an instance of it.

  • The new keyword is used to create objects in Java.

  • Each object has its own copy of instance variables.

  • The dot operator is used to access attributes and methods.

  • Multiple objects can be created from a single class.

  • Classes and objects are the foundation for all OOP concepts.

Summary of the Tutorial

In this tutorial, you learned what classes and objects are in Java and how they work together. A class acts as a blueprint, while an object represents a real entity created from that blueprint. Understanding this relationship is essential because it forms the base for everything in OOP — including constructors, attributes, methods, inheritance, and polymorphism.

Once you’re clear about how to create and use classes and objects, the rest of Java OOP becomes much easier to grasp.


Practice Questions

  1. Create a class called Employee with attributes name, id, and salary. Write a method to display employee details and create two employee objects to test it.

  2. Write a Java program to create a Car class with variables brand and price. Add a method showDetails() to print the brand and price. Create three objects with different values.

  3. Create a class named Rectangle that has two attributes length and width. Write methods to calculate and return area and perimeter of the rectangle.

  4. Build a class called Laptop with attributes brand, ram, and storage. Add a method displaySpecs() and create multiple objects to display laptop specifications.

  5. Write a Java program to create a class Person with attributes name and age. Include a method checkVotingEligibility() that prints whether the person can vote or not.

  6. Create a class named Circle with a variable radius. Add a method calculateArea() that returns the area of the circle. Create objects with different radius values and print their areas.

  7. Write a class called Movie with attributes title, genre, and rating. Add a method displayInfo() to show all details. Create two movie objects and display their data.

  8. Develop a class called BankAccount with attributes accountNumber and balance. Add methods deposit() and withdraw() to update the balance and display the current balance.

  9. Create a class called Student with attributes name, marks1, marks2, and marks3. Write a method calculateAverage() to find the average marks and print the result.

  10. Write a Java program to create a class Book with variables title, author, and price. Add a method displayBookInfo(). Create multiple book objects and display their details.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top