目录
302-方法重写介绍
303-方法重写细节
304-方法重写课堂练习1
305-方法重写课堂练习2
302-方法重写介绍
本类有这个方法就调用本类的,没有就向父类查找
303-方法重写细节
- 子类的形参列表、方法名称要和父类完全一致
- 子类的返回类型(String)可以是父类返回类型(Object)的子类,就是可以稍微不一样 ;如果反过来会报错,不兼容,冲突
- 子类方法的访问权限>=父类方法的访问权限
304-方法重写课堂练习1
305-方法重写课堂练习2
package chapter08.override;public class Person {private String name;private int age;public String say(){return "name:"+name+" age:"+age;}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}
}
package chapter08.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(){return super.say()+" id="+id+" score="+score;}public int getId() {return id;}public double getScore() {return score;}public void setId(int id) {this.id = id;}public void setScore(double score) {this.score = score;}
}
package chapter08.override;public class overrideExcercise {public static void main(String[] args) {Person jack = new Person("Jack",18);System.out.println(jack.say());Student pp = new Student("pp", 18, 12345678, 100);System.out.println(pp.say());}
}