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
- Create a class
Flowerwith fields: country of origin, shelf life in days, price. - Create classes that extend
Flower: for example, roses, carnations, tulips, and one more flower type of your choice. - Assemble 3 bouquets (use an array) and calculate the cost of each. A bouquet can contain flowers of different types.
- 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.
Task 2. Fruit stand: an abstract class and purchase cost
- Create an abstract class
Fruitand classesApple,Pear,Apricotthat extend it. - The
Fruitclass contains:
a) a weight field;
b) a completed methodprintManufacturerInfo():
c) an abstract method that returns the cost of the fruit based on its weight. This method must be overridden in every subclass.public void printManufacturerInfo() { System.out.print("Made in Ukraine"); } - Create several objects of different classes.
- Calculate the total cost of all fruit sold.
- 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().
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 inRoseorTuliponly give you counts per type. - Accessing a static field through an object. If the field is accessible,
rose.countcompiles, but it is misleading: it looks like per-object state, and IDEs flag it with a warning. Use the class name instead:Flower.countorFlower.getCount(). - Using
thisin a static method. A static method has no current object, sothisand 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