现在的位置: 首页 > 综合 > 正文

方法的重写、重载及隐藏

2013年07月30日 ⁄ 综合 ⁄ 共 1438字 ⁄ 字号 评论关闭

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

重写的概念就是顾名思义了:重新写一遍;方法名、参数及返回值是一模一样的,可能实现的过程不一样,为什么要重写?因为原来的方法不够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

抱歉!评论已关闭.