继承与接口
继承的基本用法
基本用法讲解链接:链接跳转
重写
重写是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变。
规则:
- 参数列表与被重写方法的参数列表必须完全相同
- 返回类型与被重写方法的返回类型可以不相同
- 访问权限不能比父类中被重写的方法的访问权限更低。例如:如果父类的一个方法被声明为 public,那么在子类中重写该方法就不能声明为 protected。
- 父类的成员方法只能被它的子类重写。
- 声明为 final 的方法不能被重写。
- 声明为 static 的方法不能被重写(是没有意义的,因为是直接按照父类来算),但是能够被再次声明。
- 子类和父类在同一个包中,那么子类可以重写父类所有方法,除了声明为 private 和 final 的方法。
- 构造方法不能被重写。
- 如果不能继承一个类,则不能重写该类的方法。
class Animal{
public void move(){
System.out.println("动物可以移动");
}
}
class Dog extends Animal{
public void move(){
System.out.println("狗可以跑和走");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal 对象
Dog b = new Dog(); // Dog 对象
a.move();// 执行 Animal 类的方法
b.move();//执行 Dog 类的方法
}
}
接口基础链接:添加链接描述
接口案例: 歌手大赛
接口类的方法必须是public的
public interface CompurerAverage { //接口
public double average(double x[]);
}
public class SongGame implements CompurerAverage {
public double average(double x[]) {
int count=x.length;
double aver=0,temp=0;
for(int i=0;i<count;i++) {
for(int j=i;j<count;j++) {
if(x[j]<x[i]) {
temp=x[j];
x[j]=x[i];
x[i]=temp;
}
}
}
for(int i=1;i<count-1;i++) {
aver=aver+x[i];
}
if(count>2)
aver=aver/(count-2);
else
aver=0;
return aver;
}
}
public class School implements CompurerAverage{
public double average(double x[]) {
double sum=0;
for(int i=0;i<x.length;i++){
sum+=x[i];
}
return sum/x.length;
}
}
public class Estimator{ //主类
public static void main(String args[]) {
double a[] = {9.89,9.88,9.99,9.12,9.69,9.76,8.97};
double b[] ={56,55.5,65,50,51.5,53.6,70,49,66,62,46};
CompurerAverage computer;
computer=new SongGame();
double result=computer.average(a);
System.out.printf("%n");
System.out.printf("歌手最后得分:%5.3f\n",result);
computer=new School();
result=computer.average(b);
System.out.printf("学生平均体重:%-5.2f kg",result);
}
}