Introduction to Java - Inherited method rewriting case

1. Understand what is method rewriting?

  • In the inheritance system, if the subclass has the same method declaration as the parent class, we call the method of the subclass an overridden method. 

2. Precautions and requirements for method rewriting:

  •  The name and parameter list of the overridden method must be exactly the same as the overridden method.
  • Private methods cannot be overridden.
  • When a subclass overrides a parent class method, the access rights must be greater than or equal to the parent class.
  • The subclass cannot override the static method of the parent class, if it is overridden, an error will be reported.

3. Case:

  • The functions of the old mobile phone can only be basic calls and text messages.
  • The functions of the new mobile phone need to be able to: support video calls under basic calls, and support sending voice and pictures under basic sending messages.
public class Demo {
    public static void main(String[] args) {
        //目标:认识方法重写
        NewPhone hw = new NewPhone();
        hw.call();
    }
}

/**
 *新手机:子类
 */
class NewPhone extends Phone{
    //方法的重写
    //1.重写校验注解,加上之后,这个方法必须就是正确重写的,这样更加安全。2.可提高程序的可读性,代码优雅
    //注意:重写方法的名称和形参列表必须与被重写的方法一模一样
    @Override
    public void call(){
        super.call();//调用父类的功能
        System.out.println("开始视频通话了。");
    }
    @Override
    public void sendMsg(){
        super.sendMsg();
        System.out.println("支持发语言和图片了。");
    }
}

/**
 * 旧手机:父类的
 */
class Phone{
    public void call(){
        System.out.println("打电话");
    }

    public void sendMsg(){
        System.out.println("发短信");
    }
}

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/129803408