Alexandre Santos
Alexandre Santos

Reputation: 8338

static Java Objects and day-to-day objects

There were no takers on the java room, so let me ask it here.

OOP is an object-based approach to coding, and some mapping can be done, such as saying that a mug can be represented as a Mug (Mug mug = new Mug()), and that Mug implements the Interface Grabbable. But if we follow this line of thought, what would static fields/methods be? Or is static something that cannot be mapped?

Upvotes: 2

Views: 88

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201497

In your analogy, a static method or field is something that is grouped with all Mugs but doesn't require a particular (or any) Mug to be used.

public class Mug {
  public static void doStatic() {}
  public void drink() {}
}

To drink() you need an instance of Mug, but you can call Mug.doStatic() without one. However, doStatic() cannot access this (because it isn't associated with an instance).

Edit

A static type of operation might be a factory or builder (for the creation of Mugs), it might be counting some property of Collections of Mugs, or some operation entirely unrelated to Mugs like a main method.

Upvotes: 1

Hbargujar
Hbargujar

Reputation: 400

To keep the same line of thought, consider this from real world object Mug. Mug - Green Mug - Red Mug - Blue. Considering that Shape and Size of the all three Mug is same than color would be variant property. Now consider another property of the same Mug - CAPACITY. No matter what the color of the Mug CAPACITY is same (static property of the Mug). This way we can map non-variant property (static) to Entity.

Upvotes: 0

tibo
tibo

Reputation: 5494

A static field would be a property shared by all mugs. For example numberOfMugsInTheCloset.

Non final static fields are often a bad practice though...

Upvotes: 1

Related Questions