重写
1 class Person { 2 private String name; 3 private int age; 4 public void setName(String name){this.name=name;} 5 public void setAge(int age) {this.age=age;} 6 public String getName(){return name;} 7 public int getAge(){return age;} 8 public String getInfo() { 9 return "Name: "+ name + "\n" +"age: "+ age; 10 } 11 } 12 13 class Student extends Person { 14 private String school; 15 public String getSchool() {return school;} 16 public void setSchool(String school) 17 {this.school =school;} 18 public String getInfo() { 19 return "Name: "+ getName() + "\nage: "+ getAge() 20 + "\nschool: "+ school; 21 } 22 } 23 24 public class TestOverWrite { 25 public static void main(String arg[]){ 26 Student student = new Student(); 27 Person person = new Person(); 28 person.setName("none"); 29 person.setAge(1000); 30 student.setName("John"); 31 student.setAge(18); 32 student.setSchool("SCH"); 33 System.out.println(person.getInfo()); 34 System.out.println(student.getInfo()); 35 } 36 }
在之类中可以根据需要从基类中继承来的方法进行重写
重写方法必须和被重写方法具有相同方法名称,参数列表和返回类型
重写方法不能使用比被重写方法更严格的访问权限