java - Different static fields from class and sublclasses -
i'm newbie of java, , english language not good... excuse me in advance :)
i have superclass: genericresource static field count how many instances created, , method invoke value:
public class genericresource { private static int counter; public genericresource() { counter++; } public static int howmany() { homecoming counter; } //other useful code here }
and want create semi-identical subclasses, each specific resource:
public class type1resource extends genericresource { // here specific code }
now, in 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 i'm using 2 different counter static fields, 1 superclass genericresource, , 1 subclass type1resource. desired result : howa = 2 howb = 2. real result is: howa 4 howb 4.
so i'm using same counter static field if i'm instantiate 2 different classes, while need need instead refer @ different counter static fields, 1 each subclass, mantaining @ same time, static methods construction of superclass. how can do?
static variables pertain class
, hence counter
referencing in both genericresource
, type1resource
genericresource.counter
(through implicit parameter-less constructor invocation in kid class), hence value 4
after 2 instances of each.
declare static
counter in type1resource
, , increment in specific type1resource
constructor if want count instances only.
i suggest using different name new counter well, clarity.
java
No comments:
Post a Comment