1 方法重写
1.1什么是方法重写
子类中出现了和父类中一模一样的方法声明(方法名,参数列表,返回值类型),也被称为方法覆盖,方法复写。
Override和Overload的区别?Overload能改变返回值类型吗?
@Override //注解 是用来检测此方法是不是重写父类的方法
1.2应用
当子类需要父类的功能,而功能主体子类有自己特有内容时,可以重写父类中的方法。
这样,即沿袭了父类的功能,又定义了子类特有的内容。
案例演示
a:定义一个手机类。
b:通过研究,我发明了一个新手机,这个手机的作用是在打完电话后,可以听天气预报。
public class MyTest {
public static void main(String[] args) {
Iphone iphone=new Iphone();
iphone.call();
iphone.send();
iphone.listen();
}
}
class Phone{
public Phone(){
System.out.println("构造方法执行了");
}
public void call(){
System.out.println("打电话");
}
public void send(){
System.out.println("发短信");
}
}
class Iphone extends Phone{
public void listen(){
System.out.println("听天气预报");
}
public void call(){
super.call();
System.out.println("高清视频通话");
}
}
class Huawei extends Phone{
@Override
public void call() {
}
public void send(){
}
}
1.3注意事项
a:父类中私有方法子类不能被重写
因为父类私有方法子类根本就无法继承
b:子类重写父类方法时,访问权限不能更低
最好就一致
public>protected>缺省的>private
c:父类静态方法,子类也必须通过静态方法进行重写
其实这个算不上方法重写,但是现象确实如此,至于为什么算不上方法重写,多态中
子类重写父类方法的时候,最好声明一模一样。
d:构造方法不参与重写(构造方法无法继承)
e:final修饰的方法,子类不能重写,只能继承
案例演示
方法重写注意事项
public class MyTest1 {
public static void main(String[] args) {
Father father = new Father();
father.hehe();
father.haha();
Son son = new Son();
son.hehe();
son.haha();
Son.haha();
}
}
class Father{
private void show(){
}
protected void hehe(){
System.out.println("父类的hehe方法");
}
public static void haha(){
System.out.println("父类haha的静态方法");
}
}
class Son extends Father{
protected void hehe(){
System.out.println("子类hehe方法被重写");
}
public static void haha(){
System.out.println("子类haha方法的静态方法执行了");
}
}
运行结果:
父类的hehe方法
父类haha的静态方法
子类hehe方法被重写
子类haha方法的静态方法执行了
子类haha方法的静态方法执行了
案例演示:
使用继承后的学生和老师案例
public class MyTest2 {
public static void main(String[] args) {
Teacher teacher =new Teacher();
teacher.name="Shen";
teacher.age=18;
System.out.println(teacher.name);
System.out.println(teacher.age);
teacher.sleep();
teacher.eat();
teacher.teach();
System.out.println("++++++++++++++++++++++++++++++++++");
Student student=new Student();
student.name="Tom";
student.age=10;
System.out.println(student.name);
System.out.println(student.age);
student.eat();
student.sleep();
student.talkLove();
}
}
class Person{
public String name;
public int age;
public void eat(){
System.out.println("吃饭");
}
public void sleep(){
System.out.println("睡觉");
}
}
class Teacher extends Person{
public void teach(){
System.out.println("教课");
}
public void eat(){
System.out.println("老师吃饭");
}
public void sleep(){
System.out.println("老师睡觉");
}
}
class Student extends Person{
public void talkLove(){
System.out.println("谈恋爱");
}
@Override
public void eat() {
System.out.println("学生吃饭");
}
@Override
public void sleep() {
System.out.println("学生睡觉");
}
}
运行结果:
Shen
18
老师睡觉
老师吃饭
教课
++++++++++++++++++++++++++++++++++
Tom
10
学生吃饭
学生睡觉
谈恋爱
2 方法重载
允许一个类中可以定义多个同名方法,只要他们的参数个数或参数类型不同即可,不拿返回值来区分。
2651

被折叠的 条评论
为什么被折叠?



