方法重写也叫方法覆盖,就是子类有一个方法和父类的某个方法的名称、返回类型、形参都是一样,那么这个子类的方法覆盖了父类的方法。
这里写了一个Animal类和Dog类,Dog类继承了Animal类,他们里面有一个方法是一摸一样的。
package com.edu.override_; public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String say() { return "name=" + name + "age= " +age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.edu.override_; public class Student extends Person { private int id; private double score; public String say() { return super.say() + "id=" + id + "score=" +score; } public Student(String name, int age, int id, double score) { super(name, age); this.id = id; this.score = score; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } }
package com.edu.override_; import javax.swing.plaf.synth.SynthOptionPaneUI; public class OverrideExercise { public static void main(String[] args) { Person person = new Person("jack", 30); System.out.println(person.say()); Student student = new Student("smith",19,123456 ,99.8); System.out.println(student.say()); } }