Parent class 由多个 child class 扩展,是否会为每个 [=10= 创建 parent class 的多个实例] class?
Parent class extended by multiple child classes, are there going to be multiple instances of parent class created for each child class?
如果一个parentclass被多个childclass扩展,并且所有childclass都是运行 同时,是否会在 运行 时间为每个 child class 创建多个 parent class 实例?只是好奇。
为了清楚地理解,让我们考虑下面的代码。
Parent class:
public class Parent {
public String a = "Parent";
}
Child class 1:
import org.testng.annotations.Test;
public class Child1 extends Parent {
@Test
public void child1() {
a = "Child1";
}
}
Child class 2:
import org.testng.annotations.Test;
public class Child2 extends Parent {
@Test
public void child1() {
a = "Child2";
}
}
这里想了解如果classes Child1和Child2是运行并列的,会不会有两个独立的实例(内存spaces) 为 Parent class 分别为 Child1 和 Child2 或两者创建的将共享 [=53= 的公共实例(内存 space) ] class ?
are there going to be multiple instances of parent class created for
each child class at run time ?
简短的回答是否定的。
问题是 Java 在这种情况下只会创建两个实例 - 都是子 类。每当您使用 extends
关键字时,您都会告诉 Java 扩展对象的蓝图,而不是对象本身 ,这意味着实例完全独立于彼此说说内存分配。
如果一个parentclass被多个childclass扩展,并且所有childclass都是运行 同时,是否会在 运行 时间为每个 child class 创建多个 parent class 实例?只是好奇。
为了清楚地理解,让我们考虑下面的代码。
Parent class:
public class Parent {
public String a = "Parent";
}
Child class 1:
import org.testng.annotations.Test;
public class Child1 extends Parent {
@Test
public void child1() {
a = "Child1";
}
}
Child class 2:
import org.testng.annotations.Test;
public class Child2 extends Parent {
@Test
public void child1() {
a = "Child2";
}
}
这里想了解如果classes Child1和Child2是运行并列的,会不会有两个独立的实例(内存spaces) 为 Parent class 分别为 Child1 和 Child2 或两者创建的将共享 [=53= 的公共实例(内存 space) ] class ?
are there going to be multiple instances of parent class created for each child class at run time ?
简短的回答是否定的。
问题是 Java 在这种情况下只会创建两个实例 - 都是子 类。每当您使用 extends
关键字时,您都会告诉 Java 扩展对象的蓝图,而不是对象本身 ,这意味着实例完全独立于彼此说说内存分配。