一、目录
- 方法重写介绍
- 方法重写细节
- 重写和重载的比较
- 方法重写练习
简单的说:方法重写(方法覆盖),就是子类有一个方法,和父类的某个方法的名称、返回类型、参数都一模一样。那么我们就说子类的这个方法重写了父类的那个方法。
注意: 这里所说的子类和父类并不是指只有一层的关系,重写也可以运用到多层继承上,比如爷爷类。
简单的小例子:
package com.javaoverwrite; public class OverwriteCase { public static void main(String[] args) { Dog dog = new Dog(); dog.Cry(); } } class Animal{ public void Cry(){ System.out.println("Animal Cry..."); } } class Dog extends Animal{ public void Cry(){ System.out.println("Dog Cry"); } } //Dog Cry三、方法重写细节
- 子类的方法的参数、方法名称,要和父类方法完全一样。
- 子类方法的返回类型和父类方法返回类型一样,或者是父类返回类型的子类。例如,父类返回类型是Object,子类方法返回类型是String。
- 子类方法不能缩小父类方法的访问权限。
- 编写一个Person类,包括属性private (name、age)、构造器、方法say(返回自我介绍的字符串)。
- 编写一个Student类,继承Person类,增加id、score属性(private),以及构造器,定义say方法(返回自我介绍的信息)。
- 在main中,分别创建Person和Student对象,调用say方法输出自我介绍。
package com.javaoverwrite; public class Overrideexecrise { public static void main(String[] args) { Person person = new Person("lilei", 18); Student wangbing = new Student("wangbing", 20, 2, 89.2); System.out.println(person.say()); System.out.println(wangbing.say()); } } class Person{ private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String say(){ return "hello, my name is " + this.name + " and my age is " + this.age; } } class Student extends Person{ private int id; private double score; public Student(String name, int age, int id, double score) { super(name, age); this.id = id; this.score = score; } public String say(){ return super.say() + " and my id is " + this.id + " and my score is " + this.score; } } //hello, my name is lilei and my age is 18 //hello, my name is wangbing and my age is 20 and my id is 2 and my score is 89.2