Ido Traini
Ido Traini

Reputation: 83

Different static fields from class and sublclasses

i'm newbie of Java, and my English is not so good... so excuse me in advance :)

I have a superclass: Genericresource with a static field that count how many instances are created, and a method to invoke this value:

public class Genericresource {
 private static int counter;
 public Genericresource() { counter++; }
 public static int howmany() { return counter; }
 //other useful code here
}

And i want to create some semi-identical subclasses, each for a specific resource:

public class Type1Resource extends Genericresource {

// here specific code

}

Now, in the main class:

Genericresource a1 = new Genericresource();
Genericresource a2 = new Genericresource();
Type1Resource b = new Type1Resource();
Type1Resource b2 = new Type1Resource();
int howa = Genericresource.howmany();
int howb = Type1Resource.howmany();

and i'm expecting that i'm using two different counter static fields, one for the superclass Genericresource, and one for the subclass Type1Resource. My desired result is : howa = 2 howb = 2. My real result is: howa 4 howb 4.

So i'm using the same counter static field even if i'm instantiate 2 different classes, while i need to I need instead to refer at different counter static fields, one for each subclass, mantaining at the same time, the static methods structure of the superclass. How can i do?

Upvotes: 0

Views: 45

Answers (1)

Mena
Mena

Reputation: 48404

Static variables pertain to the class, therefore the counter you are referencing in both Genericresource and Type1Resource is Genericresource.counter (through implicit parameter-less constructor invocation in child class), hence its value is 4 after two instances of each.

Declare a static counter in Type1Resource, and increment it in a specific Type1Resource constructor if you want to specifically count those instances only.

I suggest using a different name for the new counter as well, for clarity.

Upvotes: 3

Related Questions