Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a default constructor in Java

Tags:

java

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

like image 986
Pieter Avatar asked Nov 23 '25 09:11

Pieter


2 Answers

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 have to set credits or contactHours, as the int type defaults to 0 for fields anyway.

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
}
like image 122
Jon Skeet Avatar answered Nov 24 '25 21:11

Jon Skeet


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
}
like image 27
Yel Avatar answered Nov 24 '25 23:11

Yel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!