62,627
社区成员
发帖
与我相关
我的任务
分享


Human human=new Human(),
然后调用Human下面各种方法,比如human.tostring。
代码里面有一些规范化问题。比如get方法不是用来获取值的,应该被用来赋值。
public class Human{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age
}
//如果希望new的时候就给Age赋值,那么应当重新构造方法
public Human(int age){
this.age=age
}
}
还有,控制台输出应该调用System.out.println方法。System.out.println(new Human(19).toString)
还是不行的[/quote]
不好意思,getAge 方法并未返回对象,所以这么做不行,可以把 getAge 类型改成 Human,或者创建对象赋值给某个变量,然后toString。
方法1:
public Human getAge(int age) {
this.age = age;
return this;
}
调用
System.out.println(new HUman().getAge(19).toString());
方法2:
getAge方法类型不变,保持void,调用
Human human = new Human();
human.getAge(19);
System.out.println(human.toString());
[/quote]
对的,对的,我发现这个问题了,谢谢大佬
还是不行的[/quote]
不好意思,getAge 方法并未返回对象,所以这么做不行,可以把 getAge 类型改成 Human,或者创建对象赋值给某个变量,然后toString。
方法1:
public Human getAge(int age) {
this.age = age;
return this;
}
调用
System.out.println(new HUman().getAge(19).toString());
方法2:
getAge方法类型不变,保持void,调用
Human human = new Human();
human.getAge(19);
System.out.println(human.toString());
还是不行的