方法重载:方法名相同,但是具有不同的参数集合(参数个数,参数类型和参数的顺序)。
通常用于创建完成任务相似,但又不同数据类型的几个同名方法。调用时,根据参数个数,类型和顺序来选择合适的方法。方法不能由返回类型进行区分,即返回值类型可以相同也可以不同。
方法重载就是让类以统一的方式处理不同类型数据的一种手段。是类的多态性的一种表现。
example:
-
-
- import java.io.IOException;
-
- public class MethodOverloading {
- public static void main( String args[] ) throws IOException
- {
- System.out.println( "The square of integer 7 is " + square( 7 ) );
- System.out.println( "The square of double 7.5 is " + square( 7.5 ) );
- }
-
- public static int square( int n )
- {
- return n * n;
- }
-
- public static double square( double m )
- {
- return m * m;
- }
- }
result:
方法重写:如果在子类中定义某方法与其父类有相同的名称和参数,就被定义为方法重写,又称方法覆盖。只是一种父类与子类中的多态性。
如果要调用父类中的方法,则用super关键字。
子类函数的访问修饰权限不能少于父类。
example;
- public class Base {
- void test( int i )
- {
- System.out.println( i );
- }
-
- void test( double b )
- {
- System.out.println( b );
- }
- }
-
-
- public class MethodOverriding extends Base{
- void test( int i )
- {
- i++;
- System.out.println( i );
- }
-
- public static void main( String args[] )
- {
- Base b = new MethodOverriding();
- b.test( 0 );
- b.test( (double) 0 );
- }
-
- }
result: