Java私有的private的使用——按照以下要求设计一个学生类Student,并进行测试

请按照以下要求设计一个学生类Student,并进行测试。要求如下:
Student类中包含姓名、成绩两个属性
分别给这两个属性定义两个方法,一个方法用于设置值,一个方法用于获取值,其中成绩在0-100之间。
Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值
定义一个显示姓名和成绩的方法show()。
在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,另一个使用有参的构造方法,在构造方法中给姓名和成绩赋值。两个对象分别调用show()方法,输出对应的姓名和成绩。

package leiDeDingYi_leiDeShiYong;

public class Student {
  private String name;
  private float score;
  
  public Student() {//在调用的时候可以直接附上值
   setName("梨花");
   setScore(199);
  }
  public Student(String name, float score) {
   this.name = name;
   setScore(score);
  }
  public void show() {
   System.out.println("      姓名:"+name+"   成绩:"+score);
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public float getScore() {
   return score;
  }
  public void setScore(float score) {
   if(score>100||score<0) {
    System.out.print("成绩输入错误");
   this.score = score;
   }else {
    System.out.print("成绩正确信息");
    this.score = score;
    }
   }
}
package leiDeDingYi_leiDeShiYong;

public class Student2 {
  public static void main(String[] args) {
   Student st1=new Student();
   st1.show();
   Student st2=new Student("李晓",87.3f);
   st2.show();
  }
}


输出显示:
成绩输入错误      姓名:梨花   成绩:199.0
成绩正确信息      姓名:李晓   成绩:87.3
对上面的代码进行优化

package leiDeDingYi_leiDeShiYong;

public class Student3 {
  private String name;
  private float score;
  
  public Student3() {}//无参的构造方法
  public Student3(String name, float score) {
   this.name = name;
   setScore(score);//构造方法调用set成员方法
  }
  public void show() {
   System.out.println("      姓名:"+getName()+"   成绩:"+getScore());
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name; 
  }
  public float getScore() {
   return score;
  }
  public void setScore(float score) {
   if(score>100||score<0) {
    System.out.print("成绩输入错误");
   this.score = score;
   }else {
    System.out.print("成绩正确信息");
    this.score = score;
    }
   }
}
package leiDeDingYi_leiDeShiYong;

public class Student4 {
 public static void main(String[] args) {
  Student3 st1=new Student3();
  st1.setName("王晓");
  st1.setScore(139.2f);
  st1.show();
  Student3 st2=new Student3("李晓",87.3f);
  st2.show();
 }
}

成绩输入错误      姓名:王晓   成绩:139.2
成绩正确信息      姓名:李晓   成绩:87.3
发布了195 篇原创文章 · 获赞 76 · 访问量 6968

猜你喜欢

转载自blog.csdn.net/qq_45696288/article/details/105292537
今日推荐