在子类中可以根据需要对从父类中继承而来的方法进行改造,也称为重写。在执行程序时,子类的方法将覆盖父类的方法。
要求:
举个例子: Person.java
package myjava;
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void show() {
System.out.println("hello person");
}
}
Student.java
package myjava;
public class Student extends Person{
public void show() {
System.out.println("hello student");
}
}
Test.java
package myjava;
public class Test {
public static void main(String[] args) {
Person p = new Person();
Student stu = new Student();
p.show();
stu.show();
}
输出结果: hello person
hello student
可以看到,虽然Peroson类中和Student类中都存在相同的show()方法,但是里面的内容确是不一样的,在调用的时候是分别调用自己类中的方法,如果在Student类中不进行产重写show()方法,那么,最后的结果就是:
hello person
hello person
也就是都会调用父类的方法。