lotusswan

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  11 Posts :: 0 Stories :: 4 Comments :: 0 Trackbacks

为了运用多态性,当编写子类时,你肯定会覆写超类的方法。当你覆写超类的方法时,你是否想到过更改方法的返回类型。如果你没有,那祝贺你,你不曾为此烦恼过;如果你想到过,那你肯定是非常的郁闷。在Java 5.0以前,你是无法更改超类定义的方法的返回类型的。不过当你使用Java 5.0以后,你会惊喜地发现,此烦恼不复存在了。

下面的示例显示了这一新特性的用法:

package  com.jiang.tiger.chap1;

class  Point2D  {
      
protected   int  x, y;

      
public  Point2D( )  {
        
this .x = 0 ;
        
this .y = 0 ;
      }

  
      
public  Point2D( int  x,  int  y)  {
        
this .x  =  x;
        
this .y  =  y;
      }

      
      
public  String toString()  {
          
return   " the position is x =  "   +  x  +   " ,y =  "   +  y ;
      }

    }


    
class  Point3D  extends  Point2D  {
      
protected   int  z;

      
public  Point3D( int  x,  int  y)  {
        
this (x, y,  0 );
      }

 
      
public  Point3D( int  x,  int  y,  int  z)  {
        
this .x  =  x;
        
this .y  =  y;
        
this .z  =  z; 
      }

      
      
public  String toString()  {
          
return   " the position is x =  "   +  x  +   " ,y =  "   +  y  +   " ,z=  "   +  z;
      }

    }


    
class  Position2D  {
      Point2D location;
 
      
public  Position2D( )  {
        
this .location  =   new  Point2D( );
      }


      
public  Position2D( int  x,  int  y)  {
        
this .location  =   new  Point2D(x, y);
      }


      
public  Point2D getLocation( )  {
        
return  location;
      }

    }


    
public   class  Position3D  extends  Position2D  {
      Point3D location;
 
      
public  Position3D( int  x,  int  y,  int  z)  {
        
this .location  =   new  Point3D(x, y, z);
      }


      
public  Point3D getLocation( )  {
        
return  location;
      }

            
      
public   static   void  main(String[] args)  {
          Position2D position 
=   new  Position3D( 12 23 36 );
          Point3D clone 
=  (Point3D)position.getLocation();
          System.out.println(clone);
      }

    }

为验证功能是否正确,我们看看运行结果:

the position is x = 12,y = 23,z= 36

posted on 2006-11-26 23:42 lotusswan 阅读(486) 评论(0)  编辑  收藏 所属分类: Tiger学习笔记

只有注册用户登录后才能发表评论。


网站导航: