overload与override(方法重载与方法重写)

方法重载:方法名相同,但是具有不同的参数集合(参数个数,参数类型和参数的顺序)。

通常用于创建完成任务相似,但又不同数据类型的几个同名方法。调用时,根据参数个数类型顺序来选择合适的方法。方法不能由返回类型进行区分,即返回值类型可以相同也可以不同。

方法重载就是让类以统一的方式处理不同类型数据的一种手段。是类的多态性的一种表现。

example:

[java]  view plain  copy
  1. // Method overloading test  
  2.   
  3. import java.io.IOException;  
  4.   
  5. public class MethodOverloading {  
  6.     public static void main( String args[] ) throws IOException  
  7.     {  
  8.         System.out.println( "The square of integer 7 is " + square( 7 ) );  
  9.         System.out.println( "The square of double 7.5 is " + square( 7.5 ) );  
  10.     }  
  11.       
  12.     public static int square( int n )  
  13.     {  
  14.         return n * n;  
  15.     }  
  16.       
  17.     public static double square( double m )  
  18.     {  
  19.         return m * m;  
  20.     }  
  21. }  


 
result: 

方法重写:如果在子类中定义某方法与其父类有相同的名称和参数,就被定义为方法重写,又称方法覆盖。只是一种父类与子类中的多态性。

如果要调用父类中的方法,则用super关键字。

子类函数的访问修饰权限不能少于父类。

example;

[java]  view plain  copy
  1. public class Base {  
  2.     void test( int i )  
  3.     {  
  4.         System.out.println( i );  
  5.     }  
  6.       
  7.     void test( double b )  
  8.     {  
  9.         System.out.println( b );  
  10.     }  
  11. }  

[java]  view plain  copy
  1. // Methdo overriding test  
  2.   
  3. public class MethodOverriding extends Base{  
  4.     void test( int i )  
  5.     {  
  6.         i++;  
  7.         System.out.println( i );  
  8.     }  
  9.       
  10.     public static void main( String args[] )  
  11.     {  
  12.         Base b = new MethodOverriding();  
  13.         b.test( 0 );  
  14.         b.test( (double0 );  
  15.     }  
  16.   
  17. }  

result:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值