1. 基本介绍
2. 快速入门
Animal
public class Animal {
public void cry() {
System.out.println("动物叫唤..");
}
}
Dog
public class Dog extends Animal{
//解读
//1. 因为Dog 是 Animal子类
//2. Dog的 cry方法和 Animal的 cry定义形式一样(名称、返回类型、参数)
//3. 这时我们就说 Dog的cry方法,重写了Animal的cry方法
public void cry() {
System.out.println("小狗汪汪叫..");
}
}
Override01
public class Override01 {
public static void main(String[] args) {
Dog dog = new Dog();
dog.cry();
}
}
3. 注意事项和使用细节
-
- 方法重写也叫方法覆盖,需要满足下面的条件
- 但可以放大父类方法的访问权限
4. 练习
题1 :请对方法的重写和重载做一个比较
package com.xdr630.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.xdr630.override_;
public 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(){
//这里体现super的一个好处,代码复用.
return super.say() + " id=" + id + " 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;
}
}
public class OverrideExercise {
public static void main(String[] args) {
Person xdr = new Person("xdr", 23);
System.out.println(xdr.say());
Student mike = new Student("mike", 23, 12, 99);
System.out.println(mike.say());
}
}