Java之重写

来源:互联网 发布:单片机gnd是什么意思 编辑:程序博客网 时间:2024/06/08 10:07

方法的重写:


1.在子类中可以根据需要对从基类中继承来的方法进行重写


2.重写的方法必须和被重写的方法具有相同的方法名称,参数列表和返回类型


3.重写方法不能使用比被重写方法更严格的访问权限


重写(override或overwrite)和重载(overload)是不同的!!!


class Person {private String name ;private int age;public String getName() {return name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public void setName(String name) {this.name = name;}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[] args) {Student student = new Student();Person person = new Person();person.setName("none");person.setAge(1000);student.setName("john");student.setAge(18);student.setSchool("HPU");System.out.println(person.getInfo());System.out.println(student.getInfo());}}


0 0
原创粉丝点击