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

查看:781
本文介绍了在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?

其实我想要的答案在

推荐答案

许多人已经回答了如何在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)

如果你试图只创建一个对象的字节代码而不调用构造函数,你会得到一个VerifyError 。但是在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天全站免登陆