求教!还是类的问题,请多多指教.
声明一个CAT类,拥有类的变量HowManyCats,记录cat的个体数目.类方法GetHowMany(),存取HowManyCats,设计程序测试这个类,体会类变量与类方法的用法.
------解决方案--------------------哥们, 这个就自己写下吧
使用一个static域就可以了
------解决方案--------------------class Cat {
private int howManyCats;
public Cat(int catsNum) {
this.howManyCats = catsNum;
}
public int getHowMany() {
return this.howManyCats;
}
}
class TestCats{
public static void main(String[] args) {
Cat cat = new Cat(5);
System.out.println( "cat number: " + cat.getHowMany());
}
}
------解决方案--------------------拥有类的变量和类的方法。所以HowManyCats和getHowMany() 方法应该是static的。
class Cat {
public static int howManyCats = 0;
public static int getHowMany() {
return howManyCats;
}
public void setCatNum(int catNum){
howManyCats = catNum;
}
}
只需记住,静态的对象和方法不基于对象而基于类。测试如下:
class TestCats{
public static void main(String[] args) {
Cat cat1 = new Cat();
Cat cat2 = new Cat();
System.out.println( "cat1 number: " + cat1.getHowMany());
System.out.println( "cat2 number: " + cat2.getHowMany());
cat2.setCatNum(10);
System.out.println( "cat1 number: " + cat1.getHowMany());
System.out.println( "cat2 number: " + cat2.getHowMany());
}
}
结果为
0
0
10
10
------解决方案--------------------class Cat {
public static int howManyCats = 0;
public Cat(){
howManyCats++;
}
public static int getHowMany() {
return howManyCats;
}
public void setCatNum(int catNum){
howManyCats = catNum;
}
}