zoukankan      html  css  js  c++  java
  • 方法的重写、重载及隐藏

    首先,重写和隐藏是发生在两个类中的,而重载可以发生在一个类中。

    重写的概念就是顾名思义了:重新写一遍;方法名、参数及返回值是一模一样的,可能实现的过程不一样,为什么要重写?因为原来的方法不够perfect 或者不够strong,或者达不到开发者的实际应用要求。

    重载是当多个方法享有相同的名字,但是这些方法的参数不同,或者是参数的个数不同,或者是参数类型不同时。就叫方法的重载
    要注意的是:返回类型不能用来区分重载的方法,仅仅返回类型不同的两个同名方法是个error,这点比较容易理解了:如果你写参数一模一样的但是返回类型不一样的方法,当调用的时候,编译器没法决定调哪个好

    隐藏
    如下,是华为的一道面试题

    public      class      classA{   
               public      void      methodOne(int      i){      }   
               public      void      methodTwo(int      i){      }   
               public      static      void      methodThree(int      i){      }   
               public      static      void      methodFour(int      i){      }   
         }   
       
         public      class      classB      extends      classA{   
               public      static      void      methodOne(int      i){      }   
               public      void      methodTwo(int      i){      }   
               public      void      methodThree(int      i){      }   
               public      static      void      methodFour(int      i){      }   
         }   

    1     问那些方法隐藏了父类的方法?   
    2     问那些方法覆盖了父类的方法?  

    上题中的重写是很明显的,那就是methodTow.而methodOne和methodThree就比较明显的是个错误了,子类继承父类,两个相同的方法一个是static的,一个不是,你让编译器怎么实例化啊! 那剩下的就是隐藏了:static 类型的方法是不能被覆盖的;也就是说子类的methodFour写了也没用,还是调用父类的methodFour方法,因此methodFour方法隐藏了父类的方法.
    Sample:
    public class father{
           public static void overwritting(){
               System.out.print("father method");
           }
    }

    public class son extends father{
           public static void overwritting(){
               System.out.print("son method");
           }
           public static void main(String args[]){
               father son=new son();
              son.overwritting();
           }
    }
    以上程序的运行结果就是输出了:father method

  • 相关阅读:
    Css实现漂亮的滚动条样式
    清除浮动的方式有哪些?比较好的是哪一种?
    Cookie、sessionStorage、localStorage的区别
    http和https的区别?
    git 拉取分支切换分支
    css 三角形
    js中??和?.的意思
    js this指向
    tsconfig.json配置
    查看本地安装的所有npm包
  • 原文地址:https://www.cnblogs.com/zcy_soft/p/1841170.html
Copyright © 2011-2022 走看看