规则:子类继承了父类的某个方法,那么子类有权重写这个方法,子类定义的这个方法类型和父类的方法类型一致或者是父类的方法的类型的子类型,并且这个方法的名字,参数,参数类型和父类的方法完全相同
目的:子类可以通过方法的重写把父类的状态和行为改变为自身的状态和行为.
package Experience;
public class Student {
private String name="小兰";
public int age=70;
Student(){
}
Student(String name,int age){
this.name=name;
this.age=age;
}
public void show(){
System.out.println("我要上学");
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age){
if(age<=0){
System.out.println("年龄错误");
}else{
this.age=age;
}
}
public int getAge() {
return age;
}
}
package Experience;
public class Teacher extends Student {
public int age=80;
Teacher(){
super();
}
Teacher(int age){
super("小华",20);
}
@Override
public void show() {
super.show();
System.out.println("给学生上课");
}
}
package Experience;
public class Test {
public static void main(String[] args){
Teacher te=new Teacher();
te.show();
}
}