Suppose I have two classes A and B where B extends A. When I create an instance of B , constructors of both A and B get invoked. What is the best way to determine if the constructor of A is being invoked when instance B is being created?
I did something like below but it does not look very aesthetic. I am using getClass()
, is there a better approach? I am actually trying to count instances of both A and B.
public class A {
private static int counter = 0;
public A() {
if (this.getClass().getName().equals("A")) {
counter++;
}
}
public static void main(String[] args) {
A a = new B();
A a1 = new A();
A a2 = new B();
System.out.println(A.getCount());
System.out.println(B.getCount());
}
public static int getCount() {
return counter;
}
}
class B extends A {
private static int counter = 0;
public B() {
counter++;
}
public static int getCount() {
return counter;
}
}
Outputs
1
2
Well it would be better to avoid checking the name:
if (this.getClass() == A.class)
Beyond that, you could consider using a protected
constructor - but that would still be accessible within the same package.
Normally, the best solution is not to need this anyway - if your design really needs to know whether the object you're constructing is "just an A" or an instance of a subclass, then the above test represents that condition very clearly... but it's an odd requirement to start with.
See more on this question at Stackoverflow