[英]What exactly happens during object creation? (Java)
I've been studying from Head First Java and I'm currently on the constructors chapter.我一直在学习Head First Java ,目前正在学习构造函数章节。 They've explained that an object is created by calling a constructor after the new
keyword.他们已经解释过,通过在new
关键字之后调用构造函数来创建对象。
My question: What is it exactly that runs when you create a new object?我的问题:创建新对象时运行的到底是什么?
Let's take the following as sample code:让我们将以下内容作为示例代码:
public class Const {
// instance variables
int number;
String name;
// Constructors
public Const() {
//implicit super
System.out.println("no-arg constructor");
}
public Const(int i, String s) {
//implicit super()
number = i;
name = s;
System.out.println("two-arg constructor");
}
// test method
public void doSomething() {
System.out.println("I'm a test");
}
// Main
public static void main(String[] args) {
Const c1 = new Const();
Const c2 = new Const(5, "Jerry");
}
}
Now here is what I believe is happening under the hood when creating c1
:现在这是我认为在创建c1
时正在发生的事情:
public Const()
is called public Const()
被调用super()
is called super()
被调用Object
part of Const is built.构建了 Const 的Object
部分。public Const()
is back on top of the stack. public Const()
回到栈顶。What exactly happens during object creation?在对象创建过程中到底发生了什么? (Java) (爪哇)
So the only difference here is:所以这里唯一的区别是:
Const c1 = new Const();
Here number will be initialized by int default value which is 0 and name will be initialized by null , which is the default value of String这里 number 将被初始化为 int 默认值0和 name 将被初始化为null ,这是 String 的默认值
Const c2 = new Const(5, "Jerry");
Instead here it will be 5 and Jerry respecively相反,这里将分别是 5 和 Jerry
With the new Const() , the constructor will be called and the class will be loaded to the main memory.使用new Const() ,将调用构造函数并将类加载到主内存中。
public Const() {
//implicit super
super()
}
The super keyword in java is a reference variable that is used to refer parent class objects, which is by default Object class. java中的super关键字是一个引用变量,用于引用父类对象,默认为Object类。 The keyword “super” came into the picture with the concept of Inheritance.关键字“super”带着继承的概念出现了。
So now it has access of all members of Object class ie toString, equals :所以现在它可以访问 Object 类的所有成员,即 toString, equals :
as you can access你可以访问
c1.toString() or c1.equals(obj)
When and how exactly are the instance variables and methods for the object created (what implicit code is added)?对象的实例变量和方法是何时以及如何创建的(添加了哪些隐式代码)?
I think now you understood how instance variables are created, and the default values are assigned to them based on the type.我想现在你明白了实例变量是如何创建的,默认值是根据类型分配给它们的。
If still not clear, try to understand the internal arch, that might help:如果仍然不清楚,请尝试了解内部拱门,这可能会有所帮助:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.