Java的Override实现多态

来源:互联网 发布:魂斗罗水下八关mac 编辑:程序博客网 时间:2024/05/16 07:21

 方法的重写Overriding和重载Overloading是Java多态性的不同表现。重写Overriding是父类与子类之间多态性的一种表现,重载Overloading是一个类中多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。子类的对象使用这个方法时,将调用子类中的定义,对它而言,父类中的定义如同被/"屏蔽/"了。如果在一个类中定义了多个同名的方法,它们或有不同的参数个数或有不同的参数类型,则称为方法的重载(Overloading)。Overloaded的方法是可以改变返回值的类型。

1 父类

/*
 * test.java
 *
 * Created on 2008年2月27日, 下午9:47
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 
*/


package test;
import java.io.*;
/**
 *
 * 
@author rulinma
 
*/

public class test {
      
      
   
public test() {
       
//System.out.println("FatherClass Create"); 
    }

        
    
/** Creates a new instance of test */
    
public test(int i) {
        
// System.out.println("FatherClass Create"); 
    }

  
    
        
    
public void overrideProgram()
    
{
        System.out.println(
"overrideProgram Father Create"); 
    }

    
    
public static void main(String[] args)
    
{      
        
char i = '';
        System.out.println(
"i = " + i); 
     }


}

 2 子类

 

 

/*
 * child.java
 *
 * Created on 2008年2月28日, 上午10:29
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 
*/


package test;

/**
 *
 * 
@author rulinma
 
*/

public class child extends test{
   
//Another a = new Another();
    /** Creates a new instance of child */
    
public child() {
        
//System.out.println("ChildClass Create"); 
    }

    
    
public void overrideProgram()
    
{
        System.out.println(
"overrideProgram child Create"); 
    }

    
    
public static void main(String[] args)
    
{      
        test fc 
= new test(); 
        child cc 
= new child(); 
        fc.overrideProgram();
        cc.overrideProgram();
     }

}

 

运行结果:

compile-single:
run-single:
overrideProgram Father Create
overrideProgram child Create
生成成功(总时间:1 秒)

原创粉丝点击