[英]Will JVM always create instance of Object class
suppose with the following code, does JVM always create instance of Object class, since Object is parent for all the classes the in Java. 假设使用以下代码,JVM是否总是创建Object类的实例,因为Object是Java中所有类的父级。
class MyTestclass{
void printMe(String name){
System.out.println('I am '+name);
}
public static void main(String args[]){
MyTestclass obj = new MyTestclass();
obj.printMe("stackOverFlow.com");
}
}
Another class say TestClass2 另一个类说TestClass2
class TestClass2{
void printMe(String name){
System.out.println('I am '+name);
}
public static void main(String args[]){
MyTestclass obj = new MyTestclass();
TestClass2 obj2 = new TestClass2();
obj.printMe("stackOverFlow.com");
obj2.printMe("stackOverFlow.com");
}
}
Will JVM creates two object instances if i run these two classes? 如果我运行这两个类,JVM会创建两个对象实例吗?
No. There is only one object created and all the memory allocated in the name of Child, even for the field inherited from Parent. 不会。仅创建了一个对象,并且所有内存均以Child的名义分配,即使对于从Parent继承的字段也是如此。
does JVM always create instance of Object class, since Object is parent for all the classes the in Java. JVM是否总是创建Object类的实例,因为Object是Java中所有类的父级。
No. But instead JVM calls the parent constructors until it reaches the top most Object constructor which calls as constructor chaining . 不会。但是JVM会调用父构造函数,直到到达最顶层的Object构造函数为止,后者称为构造函数链接 。
Well... it depends what you mean by asking whether an instance of Object
gets created... 嗯...问您是否创建Object
实例取决于您的意思...
Remember how inheritance works. 记住继承是如何工作的。 Suppose that you have four classes: Object
, Animal
, Dog
and Terrier
. 假设您有四个类: Object
, Animal
, Dog
和Terrier
。 When you create an instance of Terrier
当您创建Terrier
的实例时
Terrier t = new Terrier();
only one instance gets created. 仅创建一个实例。 You don't get a separate Object
instance created. 您没有创建单独的 Object
实例。 But on the other hand, the point of inheritance is that a Terrier
is a Dog
, and it is an Animal
, and it is an Object
. 但另一方面,继承的要点是, Terrier
是 Dog
,它是 Animal
, 也是 Object
。 So this one instance that gets created isn't merely an Object
, but it certainly is an Object
, just like everything else. 因此,创建的这个实例不仅仅是一个Object
,而且与其他所有Object
一样,它当然是一个Object
。
So you could have written 所以你可以写
Object t = new Terrier();
or 要么
Animal t = new Terrier();
or 要么
Dog t = new Terrier();
and it would have been perfectly valid Java. 这将是完全有效的Java。
So the answer is: a single instance of a subclass of Object
gets created, and it thereby is an Object
. 因此答案是:创建了Object
子类的单个实例, 因此它是一个Object
。
Only one object is created no matter what is the inheritance hierarchy is. 无论继承层次结构是什么,都只会创建一个对象。 Features from the parent are inherited and are provided in the object of class that is used with new operator. 父级的功能部件是继承的,并在与new运算符一起使用的类的对象中提供。
MyTestclass obj = new MyTestclass();
one object with all the features of MyTestclass
and Object
class in obj
instance. 一个对象,具有obj
实例中MyTestclass
和Object
类的所有功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.