简体   繁体   English

在堆上创建对象

[英]Object creation on Heap

class Person {
    public Person(){}
}
class Employee extends Person{
    public Employee() {}
}
class Manager extends Employee{
    public Manager() {}
}
public class HeapObjectTest {
    public static void main(String[] args) {
        Manager manager = new Manager();}
}

How many object will create on the Heap for Above code?上述代码将在堆上创建多少个对象?

If we talk about only your code, then there is only one Manager object , and there will be constructor-chaining till Object class.如果我们只谈论你的代码,那么只有one Manager object ,并且会有构造函数链接到 Object 类。 Apart from this object there will be other objects also which are needed by JVM to run your program, these will be class objects, method objects which are currently loaded in to run your program.除了这个对象之外,JVM 还需要其他对象来运行您的程序,这些class objects, method objects将是class objects, method objects ,它们当前加载以运行您的程序。

For more details about the execution order of any program, to get more understanding, please read once below link,有关任何程序的执行顺序的更多详细信息,要获得更多理解,请阅读以下链接,

https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.1 https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.1

Invoking this line of code:调用这行代码:

Manager manager = new Manager();

Will create one object , an instance of the Manager class .将创建一个对象,即Manager类的一个实例。 The implementation of the Manager class borrows from the implementation of the Employee and Person classes - however, just because you inherit from those classes, doesn't mean that they get treated as separate objects. Manager类的实现借用了EmployeePerson类的实现 - 但是,仅仅因为您从这些类继承,并不意味着它们被视为单独的对象。

Your program will create only one Object for Manager class.您的程序将只为 Manager 类创建一个对象。 Manager class extends the properties/behavior of Employee and Person but it will create object for only Manager and not for others. Manager 类扩展了 Employee 和 Person 的属性/行为,但它只会为 Manager 而不是为其他人创建对象。

As per basic definition of Object- it is an instance of the class and class is just a blue print on how the object should be created.根据 Object 的基本定义 - 它是类的实例,而类只是关于如何创建对象的蓝图。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM