例:构造器,代码块在接口中统统没有,也不能创建对象
构造器的使用-----实现类
例:下图中的B类就是一个 实现类
继承只能单继承,而接口可以弥补类单继承的不足,下图中除了用student作为实现类,还可以同时使用其他类作为实现类.
接口方便业务的切换:
代码:构建了如下的接口和类
packageInterfaceDemo;
importjava.util.ArrayList;
//方案一
publicclassMethod1implementsOperate{
@Override
publicvoidprintInfo(ArrayList
for(inti=0;i
System.out.println("姓名:"+students.get(i).getName());
System.out.println("性别:"+students.get(i).getSex());
System.out.println("训练成绩:"+students.get(i).getScore());
}
}
@Override
publicvoidprintAver(ArrayList
doublesumScore=0;
for(inti=0;i
sumScore+=students.get(i).getScore();
}
System.out.println("104期学员的平均分为:"+sumScore/4);
}
}
packageInterfaceDemo;
importjava.util.ArrayList;
//方案二
publicclassMethod2implementsOperate{
@Override
publicvoidprintInfo(ArrayList
intmaleNum=0;
intfemaleNum=0;
for(inti=0;i
if(students.get(i).getSex()=='男'){
maleNum++;
}
elsefemaleNum++;
System.out.println("姓名:"+students.get(i).getName());
System.out.println("性别:"+students.get(i).getSex());
System.out.println("训练成绩:"+students.get(i).getScore());
}
System.out.println("该期学员男:"+maleNum+"人");
System.out.println("该期学员女:"+femaleNum+"人");
}
@Override
publicvoidprintAver(ArrayList
doublemax=students.get(0).getScore();
doublemin=students.get(0).getScore();
doublesumScore=0;
for(inti=0;i
if(students.get(i).getScore()>max)max=students.get(i).getScore();
if(students.get(i).getScore()
sumScore+=students.get(i).getScore();
}
System.out.println("104期学员的平均分为:"+(sumScore-max-min)/2+"分~~~");
}
}
packageInterfaceDemo;
importjava.util.ArrayList;
publicinterfaceOperate{
voidprintInfo(ArrayList
voidprintAver(ArrayList
}
packageInterfaceDemo;
publicclassStudent{
privateStringname;
privatecharsex;
privatedoublescore;
publicStudent(){
}
publicStudent(Stringname,charsex,doublescore){
this.name=name;
this.sex=sex;
this.score=score;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicchargetSex(){
returnsex;
}
publicvoidsetSex(charsex){
this.sex=sex;
}
packageInterfaceDemo;
importjava.util.ArrayList;
publicclassStuOperate{
//创建一个容器,储存学生信息
privateArrayList
privateOperateoperate=newMethod2();
publicvoidmanage(){
Students1=newStudent("米卡莎",'女',100);
Students2=newStudent("阿尼",'女',99);
Students3=newStudent("耶格尔",'男',99);
Students4=newStudent("阿尔敏",'男',99.5);
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
}
publicvoidprintAllInfo(){
operate.printInfo(students);
}
publicvoidprintAllAver(){
operate.printAver(students);
}
}
packageInterfaceDemo;
publicclasstest{
publicstaticvoidmain(String[]args){
StuOperatestuOperate=newStuOperate();
stuOperate.manage();
stuOperate.printAllInfo();
stuOperate.printAllAver();
}
}
接口好处小结: