老师,麻烦来看看,哪种稍微好点?
来源:2-9 编程练习
Acolasia丶y
2018-06-26 23:07:36
String name = "长尾猴", feature = "尾巴长";
public Monkey() {
System.out.println("我是使用无参构造的猴子");
}
public Monkey(String type, String feature) {
System.out.println("我是使用有参构造的猴子");
this.name = type;
this.feature = feature;
}
}
public class MonkeyTest {
public static void main(String[] args) {
Monkey m = new Monkey();
System.out.println("名称:" + m.name + "\n" + "特征:" + m.feature);
System.out.println("=======================");
Monkey m1 = new Monkey("白头叶猴", "头上有白毛,喜欢吃树叶");
System.out.println("名称:" + m1.name + "\n" + "特征:" + m1.feature);
}
}
这是一种按题目正规的来写的。还有下面一种,没按提示要求来,但是感觉简便一点。
public class Monkey {
String name="长尾猴",feature="尾巴长";
public Monkey(){
System.out.println("我是使用无参构造的猴子" + "\n" + "名称:" + this.name + "\n" + "特征:" + this.feature);
}
public Monkey(String name,String feature){
this();
this.name=name;
this.feature=feature;
}
}
public class Test {
public static void main(String[] args) {
Monkey m=new Monkey("白头叶猴", "头上有白毛,喜欢吃树叶");
System.out.println("我是使用有参构造的猴子" + "\n" + "名称:" + m.name + "\n" + "特征:" + m.feature);
}
}
1回答
第一种好呀,第二种虽然也有同样的输出效果,但是一旦代码量大了,代码维护太难,程序要遵守单一职责的原则。就是一个方法只一个责任,不要连带。祝:学习愉快
相似问题