JAVA构造方法练习
要求在Student类中,(task1)添加一个有name和ID两个参数的构造方法,对成员变量name和ID进行初始化,(task2)实例化一个Student对象,学生姓名:Yaoming,ID:123456,通过两次调用addScore,给总分分别加上90和95,利用getTotalScore()输出名字+总分。
注:使用System.out.println()方法输出。
public class Test { public static void main(String[] args) { //task2:write code here Student s1=new Student("Yaoming",123456); s1.addScore(90); s1.addScore(95); System.out.println(s1.getTotalScore()); } } class Student{ private String name; private int ID; private int total; //task1:write code here public Student(String name, int ID) { this.name = name; this.ID = ID; } public void addScore(int score){ total+=score; } public String getTotalScore(){ return name+":"+String.valueOf(total); } }