关于Java中的构造函数的问题 [英] Question about constructors in Java

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

问题描述

我有关于Java构造函数的几个问题

I have few questions regarding Java constructors


  1. 构造函数可以是私有的吗?

  2. 如果一个构造函数没有返回任何东西,那么为什么我们得到一个



如果没有指定,构造函数的默认访问修饰符是什么? b $ b

编辑

Edit

3都很清楚。我还不确定2&

The answers for 1 & 3 are very clear. I'm still not sure about 2 & 4 since I'm getting different answers for them.

推荐答案


  1. 是的,无论如何。然而,如果一个类的所有构造函数都是私有的,那意味着该类不能被直接实例化。您需要使用类似于工厂模式的工具来创建对象的实例。

  2. 是的,构造函数是一个方法。

  3. 一个更好的方法是, new 运算符返回对象,并在创建对象的过程中,调用构造函数。另一种思考方式(虽然这只是一种思考方式,它在技术上是不正确的)简单地说,返回类型是由约定隐含的。阅读更多相关资讯的好地方是阅读 new %2B%29rel =nofollow> C ++的上下文

  4. 在Java中,构造函数的默认访问权限是包私有的,就像任何其他方法一样。Java的构造函数不是创建对象,而是初始化对象中包含的内存。 (其中一个来源: http://www.javabeginner.com/ learn-java / introduction-to-java-access-modifiers 和马的口: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

  1. Yes, in any case. However, if all constructors for a class are private, that means that the class cannot be directly instantiated. You will need to use something like the Factory Pattern to create instances of the object.
  2. Yes, the constructor is a method.
  3. A better way to think about it is that the new operator returns the object and in the process of creating the object, calls the constructor. Another way to think about it (although this is only a way to think about it, it isn't technically correct) is simply that the return type is implied by convention. A good place to read more about this is to read about new in the context of C++. The constructor's role is not to create the object but rather to initialize the memory contained within the object.
  4. Default access for a constructor in Java is package private just like any other method. (One such source: http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers and from the horse's mouth: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)

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

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