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:
Some notes:
this.foo = foowithin the constructor. Some people avoid using the same names for parameters and fields, but I don’t personally see a problem with this.finalandprivate; 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.)numOfBiscuitsis obviously related to the biscuit.Does all of that make sense? Do ask more questions if you have them!