在 Java 中创建默认构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4366784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:35:35  来源:igfitidea点击:

Create a default constructor in Java

java

提问by Pieter

I need to create a method with a default constructor, which sets nameto an empty string and sets both creditsand contactHoursto zero. How to do it? Thanks, Pieter.

我需要创建一个默认的构造,其中规定的方法name为空字符串,并将两路creditscontactHours为零。怎么做?谢谢,彼得。

回答by Jon Skeet

Methods don't have constructors... classes do. For example:

方法没有构造函数……类有。例如:

public class Dummy
{
    private int credits;
    private int contactHours;
    private String name;

    public Dummy()
    {
        name = "";
        credits = 0;
        contactHours = 0;
    }

    // More stuff here, e.g. property accessors
}

You don't really haveto set creditsor contactHours, as the inttype defaults to 0 for fields anyway.

您实际上不必设置creditsor contactHours,因为int无论如何字段的类型默认为 0 。

You're likely to want at least one constructor which takes initial values - in which case your parameterless one can delegate to that:

您可能需要至少一个采用初始值的构造函数 - 在这种情况下,您的无参数构造函数可以委托给:

public class Dummy
{
    private String name;
    private int credits;
    private int contactHours;

    public Dummy()
    {
        this("", 0, 0);
    }

    public Dummy(String name, int credits, int contactHours)
    {
        this.name = name;
        this.credits = credits;
        this.contactHours = contactHours;
    }

    // More stuff here, e.g. property accessors
}

回答by oezi

public class Bibabu{
  private String name;
  private int credits;
  private int contactHours;

  public Bibabu(){
    name = "";         // you could also write this.name and so on...
    credits = 0;
    contactHours= 0;
  }

  // more code here

}

回答by Christian Kuetbach

You don't need a constructor:

您不需要构造函数:

public class Dummy
{
    private int credits = 0;
    private int contactHours=0;
    private String name="";
/*
    public Dummy()
    {
        name = "";
        credits = 0;
        contactHours = 0;
    }
*/  
    // More stuff here, e.g. property accessors
}

回答by user3083485

//constructor
     public Account(int id, double balance, Person owner){

        this.id = id;
        this.balance = balance;
        this.owner = owner;

回答by Yel

public class Test {
 private String name;
 private int credits;
 private int contactHours;

 public Test {

  this( "", 0, 0);

 }
public Test (String name, int credits, int contactHours) {
 this.name = name;
 this.credits = credits;
 this.contactHours = contactHours;
 }

// more code here
}