如何计算显式创建的继承树中特定类的实例数? [英] How to count the number of instances of a particular class in inheritance tree, created explicitly?
本文介绍了如何计算显式创建的继承树中特定类的实例数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A {
static int i;
{
System.out.println("A init block"+ ++i);
}
}
class B extends A {
static int j;
{
System.out.println("B init block"+ ++j);
}
}
class C extends B {
static int k;
{
System.out.println("C init block"+ ++k);
}
public static void main(String abc[])
{
C c =new C();
}
}
在上面的代码中,我们可以轻松统计数字为每个类创建的对象。
但是如果我想检查显式创建的对象的数量,我的意思是如果我使用新的C()创建C的对象,或使用新的B()创建B的对象,那么它应该相应地给出计数
In the code above, we can easily count the number of objects created for each class. But if i want to check the number of object created explicitly , i mean if I create C's object using new C(), or B's object using new B(), then it should give the count accordingly
以例如,
C c2=new C();
B b2=new B();
所以它应该将B的计数输出为1而不是2。
So it should give the output of B's count as 1 and not 2.
推荐答案
public class Foo {
private static int fooCount = 0;
public Foo() {
if (this.getClass() == Foo.class) {
fooCount++;
}
}
public static int getFooCount() {
return fooCount;
}
}
这篇关于如何计算显式创建的继承树中特定类的实例数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文