方法重写
也称为方法覆盖
,子类重写的方法必须与父类被重写的方法具有相同的方法名、参数列表和相同(或相容)的返回值类型,否则不构成重写
- 方法重写只针对实例方法,对于父类中的静态方法,子类只能隐藏、重载或继承
- 覆盖方法时,不能使用比父类中被覆盖的方法更严格的访问权限,子类只能比父类强,不能比父类弱,因为有可能将子类对象当做父类对象来使用,那么能获取到的父类对象中的方法在子类中必须都能获取到
- 父类的静态方法不能被子类重写为非静态的方法,同样,父类中的实例方法也不能被子类重写为静态方法
- 父类中能被子类继承的实例方法,才会在子类中被重写,例如父类中final修饰非方法不能重写
- 使用重写的方法时,若在子类中使用默认调用子类中的方法,在父类中使用会直接调用父类的方法
- 子类中想调用父类中被覆盖的方法,可以用“super.方法名”的格式
- 子类重写的方法不能比父类中被重写的方法声明抛出更多的异常
- 子类的方法返回值类型可以是父类方法返回值类型的子类
- 使用@Override注解,可以检查覆盖(重写)是否成功
方法重载
方法重载
是指在一个类中可以定义具有相同名字,但参数不同的多个方法,各个方法之间参数个数、参数类型、参数排列顺序至少存在一种不同,即可构成重载
- 仅有返回类型不同不能构成重载
- 方法重载是编译时多态性的表现,Java编译程序会根据方法调用的实在参数来决定使用哪个方法
- 方法重载与方法重写的区别从各自的定义就很容易区分
package inter;
//父类方法
public class Father {
private int x;
public Father(int x) {
this.x = x;
System.out.println("父类构造方法执行");
// TODO Auto-generated constructor stub
}
public Object getNum() {
return x;
}
public void overloadMethod(int x) {
System.out.println("int方法:"+x);
}
// 参数类型不同的方法的重载
public void overloadMethod(double x) {
System.out.println("double方法:"+x);
}
public final void finalMethod() {
System.out.println("final方法不能被重写");
}
public static void main(String[] args) {
Father p= new Father(1);
// 调用参数类型为double的方法
p.overloadMethod(1.0);
// 调用采参数类型为int的方法
p.overloadMethod(1);
System.out.println(p.getNum());
ChildImp child =new ChildImp(100);
// 使用覆盖父类的方法
System.out.println(child.getNum());
// 子类使用父类的final方法
child.finalMethod();
}
}
//子类方法
class ChildImp extends Father{
private int x;
public ChildImp(int x) {
super(x);
this.x = x;
System.out.println("子类构造方法执行");
// TODO Auto-generated constructor stub
}
// 重写父类方法,返回类型可以是父类方法返回值类型的子类
@Override
public Integer getNum() {
System.out.println("重写父类的方法");
System.out.println("调用父类方法:"+super.getNum());
return this.x;
}
}
运行结果
父类构造方法执行
double方法:1.0
int方法:1
1
父类构造方法执行
子类构造方法执行
重写父类的方法
调用父类方法:100
100
final方法不能被重写