Java中的构造函数和新运算符 [英] Constructor and new operator in Java

查看:179
本文介绍了Java中的构造函数和新运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要从Java中的类 Student 创建一个新对象,我们通常使用以下语句

To create a new object from a class Student in Java we use normally the following statement

Student std = new Student();

我已经读过新运算符通过在堆中分配内存空间来创建新对象,但是我还读到调用构造函数 Student()创建它。
所以,它有点令人困惑。哪一个创建对象 std ?它是 new 运算符还是默认构造函数?

I've read that the new operator creates the new object by allocating memory space in the heap, however I read also that the calling constructor Student() creates it. So, its kind of confusing. Which one is creating the object std? Is it the new operator or the default constructor?

推荐答案

这是合法的(虽然令人困惑)与类同名的方法, new 可消除任何歧义。 new 表示JVM应调用实例初始化给定类和参数列表的方法,并返回初始化对象(在初始化方法的第一个(隐藏)参数中引用)。

It's legal (though confusing) to have a method with the same name as the class, new removes any ambiguity. new indicates that the JVM should invoke the instance initialization method for the given class and argument list, and return the initialized object (referenced in the first (hidden) parameter of the initialization method).

Java的设计者可能已经找到了另一种语法,但他们的设计目标是任何时候在堆上分配内存它应该通过要求明确调出关键字 new 。这可能看起来很奇怪,但Java的大多数目标受众是C和C ++程序员,他们怀疑垃圾收集,这是为了确保开发人员在他们不知情的情况下没有分配内存。

The designers of Java could probably have found an alternative syntax, but they had a design goal that any time memory was allocated on the heap it should be called out explicitly by requiring the keyword new. This probably seems weird now but most of Java's target audience was C and C++ programmers who were suspicious of garbage collection, this was meant to make sure developers didn't have memory allocated without their knowledge.

这篇关于Java中的构造函数和新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆