Java构造函数具有默认值
读书。
我需要创建构造函数,在一个情况下,它在下面具有默认值示例。 当然,此代码是错误的,如果“狗”构造函数不会要求参数:体重,年龄并将填补班级字段:体重= 1,年龄= 1。 例如,在另一种情况下,猫会要求所有参数?这个问题通常如何解决?
public Animal(String spacies, String name, double weight, byte age, boolean isALive){
if (spacies.equals("dog")) {
this.name = name;
this.weight= 1;
this.age = 1;
this.isALive = isALive;
} else {
this.spacies = spacies;
this.name = name;
this.weight = weight;
this.age = age;
this.isALive = isALive;
}
}
thx for reading.
I need to create constructor, which in one case has default values example below.
this code is wrong of course, Is it possible to do that it means in case "dog" constructor will not ask for parameters: weight, age and will fill up class fields: weight=1, age=1.
In another case for example cat will ask for all parameters? How usually this problem is solved?
public Animal(String spacies, String name, double weight, byte age, boolean isALive){
if (spacies.equals("dog")) {
this.name = name;
this.weight= 1;
this.age = 1;
this.isALive = isALive;
} else {
this.spacies = spacies;
this.name = name;
this.weight = weight;
this.age = age;
this.isALive = isALive;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的方法是使用继承。动物是抽象实体。您应该从这些动物中获得特定的动物。
可以有不同的方法。试图提供一个简单的解决方案。
在研究OOPS概念时,请尝试与现实世界有关。
Best way is to use inheritance. Animal is abstract entity. You should derive specific animals from those.
There can be different approaches. Tried to provide one simple solution.
Try relating to real world when working on OOPS concepts.
创建一个设置这些值的第二个构造函数
Create a second constructor that sets these values