看到书中的小题,牛刀小试。
package student;
class Student{
private String name ;
private int age ;
public Student(){}
public Student(String name){
this.name=name;
}
public Student(String name,int age){
this(name);
this.age=age;
}
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void eat(){
System.out.println("不想吃");
}
public void say(Student s){
System.out.println(""+s.name+",ni给我去拿吃的");
s.bring();
}
public void bring(){
System.out.println(""+this.name+"拿来了");
}
public void bring(Student s){
System.out.println(s.name+"给"+this.name+"拿来了水果");
}
}
public class Hello01{
public static void main(String[] args){
Student[] stu=new Student[5];
Student zhang=new Student("zhangzhang ");
Student li=new Student("lili");
Student wang=new Student("wang");
Student jin=new Student("jinjin",15);
Student xie=new Student("xieie",23);
stu[0]=zhang;
stu[1]=li;
stu[2]=wang;
stu[3]=jin;
stu[4]=xie;
new Hello01().search("xieie",stu);
stu[1].eat();
stu[2].say(stu[3]);
stu[4].bring();
stu[2].bring(stu[3]);
}
public void search(Student s,Student[] stu){
if(s!=null){
System.out.println(" "+s.getName()+" "+s.getAge());
}
}
public void search(String name,Student[] stu){
for(Student s:stu){
if(name.equalsIgnoreCase(s.getName())){
System.out.print(" "+s.getName()+" "+s.getAge());
}
}
}
public void search(int age,Student[] stu){
for(Student s:stu){
if(age==s.getAge()){
System.out.print(" "+s.getName()+" "+s.getAge());
}
}
}
}
Student[] stu=new Student[5];
定义一个Student类型的数组,并动态初始化,所有的初始话值为null
在开始的时候,写了** stu[0].setName("zhangzhang");
出现错误:引用空值**
**** 清醒小刻 ****
*** 没错,我说的都是错的 ***