我们应该始终包含在类的默认构造函数? [英] Should we always include a default constructor in the class?

查看:189
本文介绍了我们应该始终包含在类的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在问这个问题的一位同事说,我们应该始终在一个类中默认的构造函数?如果是这样,为什么呢?如果没有,为什么不呢?

I have been asked this question by a colleague that should we always include a default constructor in a class? If so, why? If no, why not?

示例

public class Foo {

    Foo() { }

    Foo(int x, int y) {
        ...
    } 

}

我也有兴趣了解这一部分的灯光专家。

I am also interested to get some lights on this from experts.

推荐答案

您必须记住,如果你不提供一个重载的构造函数,编译器将生成一个默认的构造函数为您服务。这意味着,如果你只是有

You have to keep in mind that if you don't provide an overloaded constructor, the compiler will generate a default constructor for you. That means, if you just have

public class Foo
{ 
} 

,编译器会产生这样的:

The compiler will generate this as:

public class Foo
{ 
    public Foo() { }  
} 

然而,一旦你添加其他构造

However, as soon as you add the other constructor

public class Foo
{ 
    public Foo(int x, int y)
    { 
        // ... 
    }  
} 

编译器将不再自动生成默认的构造函数为您服务。 ,即$;如果类是已经在其他code这依赖于一个默认的构造函数presence,富F =新的Foo()使用C $ C现在都要碎了。

The compiler will no longer automatically generate the default constructor for you. If the class was already being used in other code which relied on the presence of a default constructor, Foo f = new Foo();, that code would now break.

如果你不希望有人能够初始化类,而不提供数据,您应该创建一个默认的构造函数是私人是明确的事实,你是被无输入数据构建preventing实例。

If you don't want someone to be able to initialize the class without providing data you should create a default constructor which is private to be explicit about the fact that you are preventing instances from being constructed with no input data.

但有时,当有必要提供一个默认的构造函数(公共或私人)。如同pviously提到的$ P $,某些类型的序列化需要一个默认的构造。还有,当一个类具有多个参数化的构造时间,但还需要较低级初始化,在此情况下私人默认的构造可以使用其从参数化的构造链中

There are times, however, when it is necessary to provide a default constructor (whether public or private). As was previously mentioned, some types of serialization require a default constructor. There are also times when a class has multiple parameterized constructors but also requires "lower level" initialization, in which case a private default constructor can be used which is chained in from the parameterized constructors.

public class Foo
{
   private Foo()
   {
      // do some low level initialization here
   }

   public Foo(int x, int y)
      : this()
   {
      // ...
   }

   public Foo(int x, int y, int z)
      : this()
   {
      // ...
   }
}

这篇关于我们应该始终包含在类的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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