一.方法重写
1.基本介绍
方法重写(覆盖)就是子类有一个方法,和父类的某个方法的名称,返回类型,参数一样,那么我们就说子类的这个方法覆盖了父类的方法
2.简单入门
public class Animal {
public void sayOk(){
System.out.println("动物叫");
}
}
public class Dog extends Animal{
public void sayOk(){
System.out.println("小狗叫");
}
}
public class Override {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sayOk();
}
}
输出结果:
老韩解读:1) 因为 Dog 是 Animal 子类
2)Dog 的 sayOk 方法和 Animal 的 sayOk 定义形式一样(名称、返回类型、参数)
3) 这时我们就说 Dog 的 sayOk 方法,重写了 Animal 的 sayOk 方法
3.使用细节
1.子类的方法的形参列表,方法名称,要和父类的形参列表,方法名称完全一样
2.子类方法的返回类型和父类方法返回类型一样, 或者是父类返回类型的子类
比如 父类 返回类型是 Object , 子类方法返回类型是 String
3.子类方法不能缩小父类方法的访问权限 (public>protected>默认>private)
4.方法的重写和重载比较
5.课后练习题2
代码
package Exercise01;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.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;
}
public String say(){
return name + " " + age;
}
}
package Exercise01;
public class Student extends Person{
private int id;
private int score;
public Student(String name, int age, int id, int score) {
super(name, age);
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String say(){
return super.say() + " " + id + " " + score;
}
}
package Exercise01;
public class Test {
public static void main(String[] args) {
Person person = new Person("jack",18);
System.out.println(person.say());
Student student = new Student("小明" , 12, 113 ,60);
System.out.println(student.say());
}
}
输出结果