一个java的小程序,不知道写得对不对,请教高手?

来源:百度知道 编辑:UC知道 时间:2024/06/24 15:50:36
创建一个Cat类,包含name和age属性,编写三个重载构造方法:Cat(),Cat(String name),Cat(String name,int age);编写两个重载成员方法:eat(),eat(String food);没有参数的eat方法默认吃鱼,有参数的eat方法吃指定的食物。
在main方法中调用这些方法
****************************************************************
public class Cat {
String name;
int age;

public Cat() {

}

public Cat(String name) {
this.name = name;
}

public Cat(String name, int age) {
this.name = name;
this.age = age;
System.out.println("姓名为" + name + ",年龄为" + age);
}

public void eat() {
System.out.println("吃鱼");
}

public void eat(String food) {
System.out.println("吃" + food);
}
}

main方法

public class Zhu {

public static void main(String[] args) {
Cat m1 = new Cat("毛毛",3);
m1.eat();
m1.eat("饼干");
}

}

呵呵 写的已经很不错了 这个阶段已经很好了
以后要主要保护成员变量 (不能直接取得)
写get方法比如
public String getName()
{
return this.name;
}
变量设置成私有的

还有最好注意下缩进 这样以后看起来比较方便 改起来也比较方便

没啥错误! 代码很对啊
不过一般属性都用private描述

没什么大错

几个地方可以改改
1.空变量的constructer可以不写;
2.attribut一般情况都要用private保护;
3.注释(至少要单行注释下attribut,重要方法)。

如果写在一个包中,应该把car类前的public去掉,一个class文件中只能有一个pubic 类,如果不是在一个包中那就是对的

养成写注释的好习惯