目录
一、方法重写
方法重写就是子类有一个方法和父类的某个方法的名称、返回类型、参数一样,那么子类的这个方法重写了父类的那个方法。
Animal类
public class Animal {
public void cry(){
System.out.println("动物世界。。");
}
}
Cat类
public class Cat extends Animal {
public static void main(String[] args) {
Cat cat = new Cat();
cat.cry();
}
public void cry(){
System.out.println("小猫。。");
}
}
1、Cat类是Ainmal的子类
2、Cat类的cry方法与Animal类的cry方法定义形式一样(名称、返回类型、参数)
3、Cat类的cry方法重写了Animal类的cry方法。
二、注意事项
1、子类的方法参数,方法名称要和父类的方法的参数,方法名称要完全一样。
2、子类方法的返回类型和父类方法返回类型一样,或者是父类返回类型的子类。
public class Animal {
//父类的返回类型是Object
public Object a1(){
return null;
}
}
public class Cat extends Animal {
public static void main(String[] args) {
Cat cat = new Cat();
cat.a1();
}
//子类的返回类型是String类型
public String a1(){
return "";
}
}
3、子类方法不能缩小父类方法的访问权限。
public class Animal {
//父类的访问权限为默认
Object a1(){
return null;
}
}
public class Cat extends Animal {
public static void main(String[] args) {
Cat cat = new Cat();
System.out.println(cat.a1());
}
//子类的访问权限为public
public String a1(){
return "aa";
}
}
三、重载与重写的比较
四、相关案例
1.编写一个Person类,包括属性/private(name,age),构造器,方法say(返回自我介绍的字符串)。
2、2.编写一个Student类,继承Person类,增加id、score属性/private,以及构造器,定义say方法(返回自我介绍的信息)。
3.在main中,分别创建Person和Student对象,调用say方法输出自我介绍。
Person类
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 + "\t年龄:" + age;
}
}
Student类
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 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 String say(){
return super.say() + "\tid:" + id + "\t成绩" + score;
}
}
public class Test01 {
public static void main(String[] args) {
Person person = new Person("张三", 22);
System.out.println(person.say());
System.out.println("Student类信息如下");
Student student = new Student("小明",13,12345,88);
System.out.println(student.say());
}
}
运行结果: