如何在Java中最好地解释和使用空构造函数? [英] How to best explain and use empty Constructors in Java?

查看:117
本文介绍了如何在Java中最好地解释和使用空构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在自学Java。我理解定义类的范围,但仍然没有得到空构造函数用法的概念。

通常我们应该传递构造函数的参数来构建实例对象。但是,我经常看到构造函数的空参数。例如:

I have been self-learning Java. I understand the scope of defining a class, but still didn't get the concept of an empty constructor usage.
Usually we should pass parameters for constructor to build instance object. But, I often see empty parameter for constructor. For example:

 class Person {
   String name;
       int age; 

 public Person();

 public Person(String name, int age){
     this.name = name;
     this.age = age;
     } 
 }

我研究并阅读了一个使用类的示例鱼解释。所以,这就是我到目前为止所理解的:在定义类时,我们首先定义一个对象的属性,然后我们创建一个构造函数,用于使用方法构建对象。空构造函数构建GENERIC对象,带有参数的构造函数构建具有更多特定信息的对象。让我们说上面的例子,如果我使用空构造函数创建一个实例对象:

I researched and read an example that using a class "fish" to explain. So, this is what I understood so far: when defining a class, we first define properties for an object, then we create a constructor that will build the object with methods. Empty constructor build GENERIC object, and constructor with parameters build objects with more specific information. Let’s say the example above, if I create an instance object using the empty constructor:

Person p1 = new Person();  

- 它仍会创建一个对象但没有任何属性?
那么,究竟空构造函数用于什么?我在很多示例代码中看到了它。这是非常有用/普通吗?

-- it will still create an object but without any properties in it? So, what exactly the empty constructor is used for? I saw it in a lot of example codes. Is it very useful/common?

感谢您的回答!

推荐答案

定义默认构造函数有三个常见原因:

There are three common reasons to define a default constructor:


  • 构造具有默认值的对象。

  • 初始化在初始化过程中不需要参数的对象。

  • 重新定义构造函数的范围。将构造函数设为私有将阻止除类本身之外的任何人构造对象。

这篇关于如何在Java中最好地解释和使用空构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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