java中构造函数的返回类型是什么? [英] What is the return type of a constructor in java?

查看:30
本文介绍了java中构造函数的返回类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我们所知,我们不必向 Java 构造函数添加任何返回类型.

As we know that we do not have to add any return type to a Java constructor.

class Sample{
  .....
  Sample(){
    ........
  }
}

在 Objective C 中,如果我们创建一个构造函数,它会返回一个指向其类的指针.但我认为这不是强制性的.

In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.

AClass *anObject = [[AClass alloc] init];//init is the constructor with return type a pointer to AClass

同理,构造函数是否转换为返回对其自身类的引用的方法??

Similarly, Is the constructor converted to a method which return a reference to its own class??

像这样:

class Sample{
    .....
    Sample Sample(){
      ........

      return this;
    }
}

编译器是否向构造函数添加了对同一类的引用的返回类型?构造函数发生了什么?有什么参考资料可以研究吗?

Does the compiler add a return type a reference to same class to constructor? What is happening to a constructor? Any reference to study this?

其实我希望答案在字节码级别或JVM级别甚至更低.

Actually i want the answers to be at byte code level or JVM level or even below.

推荐答案

很多人回答了Java中构造函数是如何定义的.

Many have answered how constructors are defined in Java.

在 JVM 级别,静态初始化器和构造器是返回 void 的方法.静态初始化器是静态方法,但是构造器使用 this 并且不需要返回任何内容.这是因为调用者负责创建对象(而不是构造函数)

At the JVM level, static initialisers and constructors are methods which return void. Static initialisers are static methods, however constructors use this and don't need to return anything. This is because the caller is responsible for creating the object (not the constructor)

如果你尝试只在字节码中创建一个对象而不调用构造函数,你会得到一个验证错误.但是在 oracle JVM 上,您可以使用 Unsafe.allocateInstance() 来创建对象,而无需调用构造函数,

If you try to only create an object in byte code without calling a constructor you get a VerifyError. However on the oracle JVM you can use Unsafe.allocateInstance() to create an object without calling a constructor,

静态初始化器称为,它不带参数,构造器称为<init>.两者都有一个 void 返回类型.

The static initialiser is called <cinit> which takes no arguments and the constructor is called <init>. Both have a void return type.

在大多数情况下,这对 Java 开发人员是隐藏的(除非他们正在生成字节码),但是只有在堆栈跟踪中看到这些方法"时(尽管你看不到返回类型)

For the most part, this is hidden from the Java developer (unless they are generating byte code) however the only time you see these "methods" in stack traces (though you can't see a return type)

这篇关于java中构造函数的返回类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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