简体   繁体   中英

Can someone explain constructors in Java?

I'm learning Java by reading the online Java book, but im finding it hard to understand "constructors". My question is how would I write a constructor that sets private fields of the class to the values received?

I've attempted this but don't think its correct:

public Biscuit(String id, String Biscuitname, int numOfBiscuits);

So if i have example "12002 digestive 83", i need a constructor that sets private fields of the class to these values received

hope this makes sense

Here you go:

public class Biscuit
{
    private final String id;
    private final String name;
    private final int count;

    public Biscuit(String id, String name, int count)
    {
        this.id = id;
        this.name = name;
        this.count = count;
    }

    // Other code
}

Some notes:

  • As the parameters and fields have the same name, I've had to use this.foo = foo within the constructor. Some people avoid using the same names for parameters and fields, but I don't personally see a problem with this.
  • I've made the fields final and private ; fields should almost always be private IMO, and final where possible - if you can make the whole type immutable, so much the better. (This leads to a more functional style of programming, which is easier to reason about and test.)
  • I've changed the names of the parameters - the name is going to be that of the biscuit, so there's no need to specify that in the parameter name, and likewise numOfBiscuits is obviously related to the biscuit.

Does all of that make sense? Do ask more questions if you have them!

Your attempt is good, but lacks implementation. Instead of a semicolon, you should write assignements to the properties separated by semicolons in curly brackets.

Simply set the fields in the body of the constructor. If the argument names from the constructor are the same as the field names in the class, then you need to prefix the class field name with this. to "disambiguate" it - Like I did with the "id" field below:

class Biscuit {
   private String id;
   private String biscuitname;
   private int numOfBiscuits;

   public Biscuit(String id, String name, String num) {
       this.id = id;
       biscuitname = name;
       numOfBiscuits = num;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM