一个父类,一个子类,子类new出三个实例,父类有没有被new出来?new出来几个,在线求解。
例子代码:class A{
public void cc(){
System.out.println("nihao");
}
}class B extends A{
public void cc(){
System.out.println("hello");
}
public static void main(String[] args){
B b1=new B();
B b2=new B();
B b3=new B();
//如果把b1,b2,b3都设为null,java回收会回收几个object?
}
}
例子代码:class A{
public void cc(){
System.out.println("nihao");
}
}class B extends A{
public void cc(){
System.out.println("hello");
}
public static void main(String[] args){
B b1=new B();
B b2=new B();
B b3=new B();
//如果把b1,b2,b3都设为null,java回收会回收几个object?
}
}
你可以在父类中写无参的构造方法,打印语句,在子类中也写无参的构造方法,打印语句,这样运行时就可以看到父类是否被new出来,以及new了几个。
二楼说的只是调用了父类的构造方法而已,这个我知道,但是并不代表会产生父类实例。
static int count;
public Father(){
count++;
System.out.println("Father Construct"+count);
}
protected void finalize() throws Throwable {
System.out.println("FatherBye!");
super.finalize();
}}
class Child extends Father{
static int c ;
public Child(){
c++;
System.out.println("Child Construct"+c);
}
protected void finalize() throws Throwable {
System.out.println("Bye!");
super.finalize();
}
public static void main(String[] args){
Child c1 = new Child();
Child c2 = new Child();
Child c3 = new Child();
c1=null;
c2=null;
System.gc();
}
}运行结果:
Father Construct1
Child Construct1
Father Construct2
Child Construct2
Father Construct3
Child Construct3
Bye!
FatherBye!
Bye!
FatherBye!我试了下,当对象指为空时,自己主动调用gc,此时会调用finalize方法,结果说明父类的和子类的finalize都调用了,所以结果应该是三个父类的对象,三个子类的对象。真正回收时都需要回收。此为个人理解,如有误,还望指教。