1、在子类中可以根据需要对从基类中继承的方法进行重写
2、重写方法必须和被重写方法具有相同对的方法名称,相同的参数列表和返回值类型
3、重写方法不能使用比被重写方法更严格的访问权限
在方法重写的时候注意:对那个方法进行重写尽量copy那个方法,如果在重写
getInfo这个方法时,不小心写成了GetInfo当编译的时候,不会报错,但是得不到你想要的结果
例如:
class Person {
private String name;
private int age;
public void setName(String name){this.name=name;}
public void setAge(int age) {this.age=age;}
public String getName(){return name;}
public int getAge(){return age;}
public String getInfo() {
return "Name: "+ name + "\n" +"age: "+ age;
}
}
class Student extends Person {
private String school;
public String getSchool() {return school;}
public void setSchool(String school)
{this.school =school;}
public String getInfo() {
return "Name: "+ getName() + "\nage: "+ getAge()
+ "\nschool: "+ school;
}
}
public class TestOverWrite {
public static void main(String arg[]){
Student student = new Student();
Person person = new Person();
person.setName("none");
person.setAge(1000);
student.setName("John");
student.setAge(18);
student.setSchool("SCH");
System.out.println(person.getInfo());
System.out.println(student.getInfo());
}
}