public class A { private static int count = 0; public A() { count++; } public static int getObjectNumber() { return count; } }
class B { //次方法中要用到count的值,该如何呢?} public class A { private static int count = 0;//用count来记录B对象的个数 B a=new B(); B b=new B(); B c=new B(); }
//能不能具体点 class B { //此方法中要用到count的值,该如何来做呢?} public class A { private static int count = 0;//用count来记录B对象的个数 B a=new B(); B b=new B(); B c=new B(); }
package temp;import java.lang.String; import java.io.*;public class Test { private static int i = 0; public Test() { i++; } public static int getNum() { return i; }}class Other { public static void main(String[] args) { Test t = new Test(); Test t1 = new Test(); Test t2 = new Test(); Test t3 = new Test(); Test t4 = new Test(); Test t5 = new Test(); Test t6 = new Test(); Test t7 = new Test(); System.out.println("一共创建了" + Test.getNum() + "个对象"); } } 运行结果: 一共创建了8个对象不过这样实现有peacedog()说的问题
iambic() ( ) 信誉:100 Blog public class A { private static int count = 0; public A() { count++; } public static int getObjectNumber() { return count; } } 这个办法好啊~~ peacedog() ( ) 信誉:100 Blog 其实这个办法不够完全,当一个对象不再使用的时候,应该减去对象的引用数,从目前这个实现来看,对象的引用数只有增加而没有减少。 可以为对象定义finalize方法~~ 在次方法中实现count--;
可以有2种方法:1.定义一个静态变量啊,private static int number; 在类的构造方法里让改变量自增: number++; 在类里提供一个可以获取 number的方发用来获取number的值2.还有一种方法,就是在生成对象的时候,使用数组或者链表啊容器啊一类的数据结构来进行管理。 比如你定义的类是A ,你可以定义一个数组 A a = new A[5]。
private static int count = 0;}
private static int count = 0;
public A() {
count++;
}
public static int getObjectNumber() {
return count;
}
}
{ //次方法中要用到count的值,该如何呢?}
public class A
{
private static int count = 0;//用count来记录B对象的个数
B a=new B();
B b=new B();
B c=new B();
}
class B
{ //此方法中要用到count的值,该如何来做呢?}
public class A
{
private static int count = 0;//用count来记录B对象的个数
B a=new B();
B b=new B();
B c=new B();
}
import java.io.*;public class Test {
private static int i = 0; public Test() {
i++;
} public static int getNum() {
return i;
}}class Other {
public static void main(String[] args) {
Test t = new Test();
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
Test t4 = new Test();
Test t5 = new Test();
Test t6 = new Test();
Test t7 = new Test();
System.out.println("一共创建了" + Test.getNum() + "个对象");
}
}
运行结果:
一共创建了8个对象不过这样实现有peacedog()说的问题
你感兴趣可以找来看看代码.
public class A {
private static int count = 0;
public A() {
count++;
}
public static int getObjectNumber() {
return count;
}
}
这个办法好啊~~
peacedog() ( ) 信誉:100 Blog
其实这个办法不够完全,当一个对象不再使用的时候,应该减去对象的引用数,从目前这个实现来看,对象的引用数只有增加而没有减少。
可以为对象定义finalize方法~~
在次方法中实现count--;
在类的构造方法里让改变量自增: number++;
在类里提供一个可以获取 number的方发用来获取number的值2.还有一种方法,就是在生成对象的时候,使用数组或者链表啊容器啊一类的数据结构来进行管理。
比如你定义的类是A ,你可以定义一个数组 A a = new A[5]。