Follow

Is there a good way to combine these two setFoodName?

@Acer overwrite the FoodName member.. you are hard-coding it anyways, why bother setting it in the constructor?

@Acer since Tomato() is only a special case of Tomato(int size), you may try

Tomato(){ this(_default_size); }

not sure, I’m no java expert XD

@Acer And I don't think it's a good idea to call setFoodName in the constructor. Say you want to change the food name from "Tomato" to "StrangeRedApple", you have to rewrite every single function attribute.

I would simply set the member foodName to "Tomato", and every time you need the name, you do "this.foodName" or "getFoodName()"..

@shrik3

it will throw error if writing foodName directly.
I dont know the exact reason. maybe it is because foodname is private variable of Food instead of Tomato

@Acer if all you're wanting is to reduce a line of code I wouldn't bother lol

@Acer Whatever the language, shouldn't the function be able to have an 'optional input' so you can set a default if no input is found?

@Acer Looks like Java doesn't have optional parameters. Another reason for me to try to forget this language even exists. ;)

Java does have some tricks to mimic this. Check this page, it gave me some idea about those tricks:
stackify.com/optional-paramete

@trinsec

The tricks on the page is not applied to constructor or I already applied accessors

@Acer Tomato (){this(121)}不知道你指的是不是这个意思

@miaomaiohome

java沒有這個語法好像 看不懂這個表達式意思

@Acer java是不能设置默认参数, 起码得两个构造函数。this(121)这一行调用自己的带参数构造函数。this是自己这个类的意思

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.