java中构造方法是否有返回值

更新时间:02-07 教程 由 果儿 分享

java中构造方法是否有返回值?

按照官方文档描述,java中构造方法是不具有返回值的。

下面是原文:

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }

To create a new object called , a constructor is called by the operator:

Bicycle myBike = new Bicycle(30, 0, 8);

creates space in memory for the object and initializes its fields.

Although only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() { gear = 1; cadence = 10; speed = 0; }

invokes the no-argument constructor to create a new object called .

Both constructors could have been declared in because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of , which does have a no-argument constructor.

You can use a superclass constructor yourself. The class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.

You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.

Note: If another class cannot call a constructor, it cannot directly create objects.

译文如下:

为你的类提供构造方法

一个类包含多个构造方法,这些构造方法用于从类定义中创建对象。构造方法声明很像方法声明——除了它们使用的是类名作为方法名并且没有返回类型。举个例子,Bicycle 有一个构造方法:public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed;}为了创建名为myBike的一个新的Bicycle对象,构造方法被new操作符调用:Bicycle myBike = new Bicycle(30, 0, 8);new Bicycle(30, 0, 8)在内存中为对象创建了空间并且初始化了它的属性。目前Bicycle只有一个构造方法,但是同时,它可以有更多构造方法,包括一个无参构造方法:public Bicycle() { gear = 1; cadence = 10; speed = 0;}...还有其他不做翻译

Java官方文档也描述有:对于构造方法来说,它与类方法类似,但是没有返回类型,也意味着没有返回值。

而为什么我们可以直接通过new来获得一个返回值,那是因为new是一个操作符,new这个操作符调用了构造方法,并且返回了通过new操作符在内存中创建的空间地址。

结论:无返回值

声明:关于《java中构造方法是否有返回值》以上内容仅供参考,若您的权利被侵害,请联系13825271@qq.com
本文网址:http://www.25820.com/tutorial/14_2314376.html