public class Bird
{
private static int id = 0;
private String kind;
public Bird(String requiredKind)
{
id = id + 1;
kind = requiredKind;
}
public String toString()
{
return "Kind: " + kind + ", Id: " + id + "; ";
}
public static void main(String [] args)
{
Bird [] birds = new Bird[2];
birds[0] = new Bird("falcon");
birds[1] = new Bird("eagle");
for (int i = 0; i < 2; i++)
System.out.print(birds[i]);
System.out.println();
}
}
这是一个样本考试的问题,输出被询问,正确答案是Kind:falcon,Id:2;种类:鹰,Id:2;
这有什么意义?对于猎鹰不应该是1,那么鹰,因为它的静态id将是2?
答案 0 :(得分:3)
private static int id = 0;
static
表示所有实例都将共享值
因此,每次实例化Bird
时,值都会增加
public Bird(...){
id = id + 1;
}
Bird bird1 = new Bird("faclon"); // id = 1
Bird bird2 = new Bird("eagle"); // id = 2
System.out.println(birdl); // falcon id 2
System.out.println(bird2); // eagle id 2
假设您这样做了
Bird bird1 = new Bird("falcon"); // id = 1
System.out.println(bird1); // falcon id = 1
Bird bird2 = new Bird("eagle"); // id = 2
System.out.println(bird2); // eagle id 2
System.out.println(bird1); // falcon id = 2
Bird bird = new Bird("elephant"); // id = 3
System.out.println(bird1); // falcon id 3
区别在于打印报表的位置。
编辑:获取所需的输出
Bird[] birds = new Bird[2];
String[] birdNames = {"falcon", "eagle"};
for (int i = 0; i < birds.length; i++){
birds[i] = new Bird(birdNames[i]);
System.out.println(birds[i]);
}
在上面的代码中,您将获得
种类:猎鹰id:1
善良:老鹰身份:2
答案 1 :(得分:2)
public class Bird
{
private static int id = 0; //initial value of id =0;
private String kind;
public Bird(String requiredKind)
{
id = id + 1; //for first bird 0+1 so id=1 ,second bird 1+1 so id=2
kind = requiredKind;
}
public String toString()
{
return "Kind: " + kind + ", Id: " + id + "; "; //here return the values
}
public static void main(String [] args)
{
Bird [] birds = new Bird[2];
birds[0] = new Bird("falcon"); // id = 1
birds[1] = new Bird("eagle"); // id = 2
for (int i = 0; i < 2; i++) // here loop for string values
System.out.print(birds[i]);
System.out.println();
}
}