static ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-09-26

static. Practical Tasks

A common beginner mistake: add an int count field to a class and increment it in the constructor. After three calls to new, every object still reports count == 1, because without static each object gets its own copy of the counter. Both tasks below train you to avoid exactly this mistake.

The static keyword in Java makes a variable or method belong to the class itself rather than to any single object. A static variable exists in a single copy shared by the whole class, and every object sees the same value. That is why it is used for object counters, running totals, and constants.

This page contains two Java static keyword exercises that also practice inheritance and abstract classes: a flower shop with a counter of sold flowers, and a fruit stand that calculates purchase cost. Each task comes with a ready-made solution.

What you need to know before you start

The most common use of static is counting how many objects of a class have been created. A static counter is incremented in the constructor and is shared by every instance:

public class Flower {
    private static int count = 0; // a single copy shared by the whole class

    public Flower() {
        count++;
    }

    public static int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        new Flower();
        new Flower();
        new Flower();
        System.out.println(Flower.getCount()); // 3
    }
}

How a static variable differs from a regular instance variable:

Characteristic Instance variable Static variable (static)
Who owns it A specific object The class as a whole
How many copies One per object One per class (shared with all its subclasses)
How to access it obj.field ClassName.field
Typical use Object state: price, weight, country Object counters, running totals, constants

Task 1. Flower shop: a counter of sold flowers

  1. Create a class Flower with fields: country of origin, shelf life in days, price.
  2. Create classes that extend Flower: for example, roses, carnations, tulips, and one more flower type of your choice.
  3. Assemble 3 bouquets (use an array) and calculate the cost of each. A bouquet can contain flowers of different types.
  4. Count the total number of flowers sold, that is, all flowers across every bouquet you assembled (use a static variable).

Hint: a static variable declared in Flower is shared by the whole class and all of its subclasses. If you increment it in the Flower constructor, the counter picks up roses, tulips, and carnations alike.

Solution on Patreon →

Task 2. Fruit stand: an abstract class and purchase cost

  1. Create an abstract class Fruit and classes Apple, Pear, Apricot that extend it.
  2. The Fruit class contains:
    a) a weight field;
    b) a completed method printManufacturerInfo():
    public void printManufacturerInfo() {
        System.out.print("Made in Ukraine");
    }
    c) an abstract method that returns the cost of the fruit based on its weight. This method must be overridden in every subclass.
  3. Create several objects of different classes.
  4. Calculate the total cost of all fruit sold.
  5. Separately calculate the total cost of apples, pears, and apricots sold.

Hint: it is convenient to accumulate the grand total and the per-type totals in static fields. Keep the grand total in Fruit, and keep the per-type totals in the subclasses.

Watch out

It is tempting to add the cost to the static total right inside the Fruit constructor by calling the abstract cost method. Be careful: the parent constructor runs before the subclass fields are initialized, so if Apple stores its price per kilogram in an instance field, the overridden method will see 0 there. Either update the totals in the subclass constructor (after super(...)) or in a separate method such as sell().

Solution on Patreon →

Where developers get tripped up

  • A counter without static. Each new object gets its own copy of the field starting at 0, increments it once in the constructor, and so every object reports 1.
  • A counter in every subclass instead of the base class. If you need the total number of flowers, the counter must live in Flower. Separate counters in Rose or Tulip only give you counts per type.
  • Accessing a static field through an object. If the field is accessible, rose.count compiles, but it is misleading: it looks like per-object state, and IDEs flag it with a warning. Use the class name instead: Flower.count or Flower.getCount().
  • Using this in a static method. A static method has no current object, so this and instance fields are not accessible inside it.

Before submitting your solution, review it against common Java code style guidelines: meaningful English names, one public class per file, and consistent formatting.

Frequently asked questions

Can you access a non-static variable from a static method?

Not directly: a static method is called without an object, so it has no this. The code will not compile and fails with "non-static variable cannot be referenced from a static context". To read an instance field, first create an object or pass one into the method as a parameter.

Can you override a static method in Java?

No. A static method with the same signature in a subclass does not override the parent's method — it hides it (method hiding). Which method gets called is decided by the reference type at compile time, not by the object's actual type, so polymorphism does not apply to static methods.

Is a parent class's static variable shared by all subclasses?

Yes. A static field declared in Flower exists as a single copy, and every subclass (Rose, Tulip, and others) works with that same copy. A separate copy appears only if a subclass declares its own field with the same name, which is not recommended: it leads to field hiding and confusion.

Is a static int count counter with count++ thread-safe?

No. The count++ operation is not atomic, and when objects are created concurrently from multiple threads, some increments can be lost. For learning exercises this does not matter. In multithreaded code, use AtomicInteger or synchronization instead.

Comments

Please log in or register to have a possibility to add comment.