• Java类的继承与方法调用的一个小问题


     1 public class Father {
     2 
     3     protected void server(int i){
     4         switch (i){
     5             case 1:
     6                 methodone();
     7                 break;
     8             case 2:
     9                 methodtwo();
    10                 break;
    11             case 3:
    12                 methodthree();
    13                 break;
    14             default:
    15                 System.out.println("error");
    16         }
    17 
    18 
    19 
    20     }
    21 
    22     protected void methodthree() {
    23         System.out.println("这是父类的方法三");
    24     }
    25 
    26     protected void methodtwo() {
    27         System.out.println("这是父类的方法二");
    28     }
    29 
    30     protected void methodone() {
    31         System.out.println("这是父类的方法一");
    32     }
    33 }
     1 public class Child extends Father {
     2 
     3     @Override
     4     protected void methodthree() {
     5         System.out.println("这是子类的方法三");
     6     }
     7 
     8     @Override
     9     protected void methodtwo() {
    10         System.out.println("这是子类的方法二");
    11     }
    12 
    13     @Override
    14     protected void methodone() {
    15         System.out.println("这是子类的方法一");
    16     }
    17 
    18     @Override
    19     protected void server(int i) {
    20         super.server(i);
    21     }
    22 }
    1 public class Test_main {
    2     public static void main(String[] args){
    3         Father fa=new Father();
    4         Father ch=new Child();
    5         fa.server(1);
    6         ch.server(2);
    7 
    8     }
    9 }

      在学习servlet的过程中突然对类方法的调用关系犯了糊涂,所谓基础不牢,地动山摇,一个小问题足以搞得我模模糊糊。在类的继承中,子类继承父类的某个方法,若这个方法中含有对父类的另一个方法(如method1,method2,method3)的调用,当子类不重载此方法(如method1,method2,method3)时,编译器会自动调用父类的相应的方法;当子类重载此方法(如method1,method2,method3)时,编译器会自动调用子类重载的方法。

      换句话说,子类继承父类方法时只是继承了相应的代码,父类调用子类的实例时会接着调用子类重载的方法,方法没有被子类重载时才会调用父类本来的方法。

  • 相关阅读:
    Windows Server 2016-安装AD域服务注意事项
    Windows Server 2016-WinSer2016 Active Directory新增功能
    Windows Server 2016-Active Directory域服务概述
    MDT 2013 从入门到精通之概念扫盲
    SpringBoot | 第五章:多环境配置
    SpringBoot | 第四章:日志配置(转)
    SpringBoot | 第三章:springboot配置详解
    SpringBoot | 第二章:lombok介绍及简单使用
    SpringBoot | 第零章:前言
    转自IBM:Apache HTTP Server 与 Tomcat 的三种连接方式介绍
  • 原文地址:https://www.cnblogs.com/Yin-BoKeYuan/p/10329957.html
Copyright © 2020-2023  润新知