1.重写:子类继承父类以后,可以对父类中同名同参数的方法,进行覆盖操作
2.应用:重写以后,当创建子类对象以后,通过子类对象调用子父类中的同名同参数的方法时,
实际执行的是子类重写父类的方法。
3. 重写的规定:
权限修饰符 返回值类型 方法名(形参列表) throws 异常的类型{
//方法体
}
一般称子类中的叫重写的方法,父类中的叫被重写的方法
1、子类重写的方法的方法名和参数列表与父类被重写的方法的方法名和参数列表相同
2、子类重写的方法的权限修饰符不能小于父类被重写的方法的权限修饰符
>特殊情况:子类不能重写父类中声明为private权限的方法
3、 返回值类型:
>父类被重写的方法的返回值类型是void,则子类重写的方法的返回值类型只能是void
>父类被重写的方法的返回值类型是A类型,则子类重写的方法的返回值类型可以是A类或A类的子类
>父类被重写的方法的返回值类型是基本数据类型(比如:double),则子类重写的方法的返回值类型必须是相同的基本数据类型(必须也是double)
4、 子类和父类中的同名同参数的方法要么都声明为非static的(考虑重写),要么都声明为static的(不是重写)。
public class Number {
public static void main(String[] args) {
Num1 num1=new Num1();
num1.eat("张三");
Num2 num2=new Num2();
num1.eat("张三");
num2.eat("李四");
// 继承之后,play方法自动有的,eat方法也是
num2.play();
}
}
class Num1{
String name;
public Num1(){
}
public Num1(String name){
this.name=name;
}
// 方法eat
public void eat(String name){
System.out.println("我叫"+name+",我爱吃肉");
}
public void play(){
System.out.println("玩");
}
}
class Num2 extends Num1{
// 重写方法eat
public void eat(String name){
System.out.println("我叫"+name+",我爱吃素");
}
}