Real Life Example to use Static Methods and Variables

In this class, We discuss Real Life Examples of using Static Methods and Variables.

The reader should have prior knowledge of static variables in Java. Click here.

Example:

Take a movie theatre example.

We need to develop an application for booking movie tickets.

The below example is a class in our application.

class bookmovietickets

{

static int totalticketssold;

int numberoftickets;

static void totaloccupied()

{

}

void bookaticket()

{

}

}

In the above example, we took a static variable.

Why the variable “total tickets sold” is static?

Why the method “total occupied” is static?

We understand the above questions.

Suppose a user logs into our web application and needs to buy tickets.

One user will buy two tickets, and another may buy six tickets.

Each user should have their our memory to store tickets count.

We consider the number of tickets as instance variables to allocate objects for each user.

After buying tickets, each user has to update the total tickets count.

The variable “total tickets sold” should be used by every object. i.e. every user.

We consider the variable “total tickets sold” to be static.

Similarly, the method of total occupied uses a static variable. So we consider the static method.

Another reason is that the method “total occupied” should be used without creating an object so static.

This example will help the users to understand the use of static and instance variables.