Try to change the variable to static, so its value will be independent of the instance to which it is linked:
private static int nInstancias = 0;
and within the builder of A
:
public A(){
nInstancias++;
...
}
Note: Since the other classes extend from A, the counter will increment each time an instance of B and C is created as well. See the test:
public class ClasseA {
private static int instances = 0;
public ClasseA() {
instances++;
}
public static int getNumberInstances(){
return instances;
}
public static void main(String[] args) {
System.out.println("Instanciando ClasseA...");
ClasseA a = new ClasseA();
System.out.println("No. de instancias: " + ClasseA.getNumberInstances());
System.out.println("Instanciando ClasseB...");
ClasseB b = new ClasseB();
System.out.println("No. de instancias: " + ClasseA.getNumberInstances());
System.out.println("Instanciando ClasseC...");
ClasseC c = new ClasseC();
System.out.println("No. de instancias: " + ClasseA.getNumberInstances());
}
}
class ClasseB extends ClasseA {
}
class ClasseC extends ClasseA{
}
Upshot:
Instanciando ClasseA...
No. de instancias: 1
Instanciando ClasseB...
No. de instancias: 2
Instanciando ClasseC...
No. de instancias: 3
Working: https://ideone.com/gPyfaD
Reference:
private int nInstancias = +;
This is not a valid java statement,– user28595
sorry error. had not repaired @Articuno
– skidils