方法的重寫:
1、在子類中可以根據需要對從基類中繼承來的方法進行重寫。
2、重寫的方法和被重寫的方法必須具有相同方法名稱、引數列表和返回型別。
3、重寫方法不能使用比被重寫的方法更嚴格的訪問許可權。
程式code:
class Person{ private int age; private String name; public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public String getName(){ return name; } public String getInfo(){ return "Name is:"+name+",Age is "+age; } } class Student extends Person{ private String school; public void setSchool(String school){ this.school = school; } public String getSchool(){ return school; } public String getInfo(){ return "Name is:"+getName()+",Age is "+getAge()+",School is:"+school; } } public class TestOverRide{ public static void main (String args[]){ Student student = new Student(); Person person = new Person(); person.setAge(1000); person.setName("lili"); student.setAge(23); student.setName("vic"); student.setSchool("shnu"); System.out.println(person.getInfo()); System.out.println(student.getInfo()); } }
執行結果: