关于覆盖与隐藏

来源:互联网 发布:unity3d寻路插件 编辑:程序博客网 时间:2024/05/02 01:47
 public class TestExtends {
    public static void main(String [] args){
        IDog d1 = new Dog();
        d1.check();
        IDog d2 = new BullDog();
        d2.check();
        Dog d3 = (Dog)d2;
        d3.check();
        Dog d4 = new BullDog();
        d4.check();
        BullDog d5 = new BullDog();
        d5.check();
    }
}

interface IDog{
    public void check();
}

class Dog implements IDog{
    private String bort() {
        // TODO Auto-generated method stub
        return "wangwang";
    }

    public String getName() {
        // TODO Auto-generated method stub
        return "Dog";
    }

    public void check() {
        // TODO Auto-generated method stub
        System.out.println(this.getName() + "-" + this.bort());
    }
    
}

class BullDog extends Dog{
    private String bort() {
        // TODO Auto-generated method stub
        return "woowoo";
    }

    public String getName() {
        // TODO Auto-generated method stub
        return "BullDog";
    }
}



***************************************************
public   class   planet{  
          public   static   void   hide(){  
                  System.out.println("The   hide   method   in   Planet.");  
          }  
          public   void   override(){  
                  System.out.println("The   override   method   in   Planet.");  
          }  
  }  
   
  public   class   earth   extends   planet{  
          public   static   void   hide(){  
                  System.out.println("The   hide   method   in   Earth.");  
          }  
          public   void   override(){  
                  System.out.println("The   override   method   in   Earth.");  
          }  
          pubilc   ststic   void   main   (String[]   args){  
                Earth   myEarth=new   Earth();  
                Planet   myPlanet=(Planet)myEarth;  
                myPlanet.hide();  
                myPlanet.override();  
                }  
  }  
   
   
  输出  
  the   hide   method   in   Planet.  
  The   override   method   in   Earth.  
   
  是怎么得来的,哪一句是控制输出的?  
   
    myPlanet.hide();  
                myPlanet.override();  
  这两句能说说什么意思嘛?

***************************
static方法不能覆盖,private方法也不能覆盖。Java视它们为被隐藏.  
   
  在Planet里hide()是static,所以当earth   也有hide()时,Java视Planet里hide()被隐藏.  
  所以myPlanet.hide();是Planet里的。  
   
  因为Planet里的override()不是static,也不是private,所以当earth   也有override()时,  
  这是重载,不会理会Planet里的override()了。myPlanet.override()就是earth里的.  
   
  当使用   Planet   myPlanet=(Planet)myEarth;时,一定是使用的Planet里的static方法。  
  当使用   Earth   myEarth=new   Earth();   时,如果myEarth里有override();一定不会用Planet里的override(); 方法。  
   
  当使用Earth   myEarth=new   Earth();一定是使用的Earth里的static方法,因为Java视static也就是hide()为被隐藏.不会再用了。  
   
   
  说完了,自己也晕了。  
  不知道说明白没有。  
   


原创粉丝点击