interface sport
{
void run();
void jump();
}
class Athlete implements sport
{
public void run()
{
System.out.println("run");
}
/*public void jump()
{
System.out.println("jump");
}*/

public static void main(String [] args)
{
Athlete zhang = new Athlete();
zhang.run();
zhang.jump();
}
}
如果我把class Athlete中的
public void jump()
{
System.out.println("jump");
}注释掉,为什么不能编译?提示:Athlete不是抽象的,并且没有覆盖sport中的jump()
我不想调用sport中的jump方法,应该怎么做?

解决方案 »

  1.   

    implements sport 就要实现他内部的方法 
      

  2.   

    你可以把Athlete写成抽象类,由他的子类生成实例abstract class Athlete implements sport{
        public void run()
        {
            System.out.println("run");
        }
    }
    class SubAthlete extends Athlete {    public static void main(String [] args)
        {
            Athlete zhang = new SubAthlete ();
            zhang.run();
            zhang.jump();
        }}
      

  3.   

    楼上的做法也不行的。SubAthlete还是要实现jump()方法的!接口中的方法最终必须全部实现,否则,就失去定义接口的意义了。接口不是定义出来摆摆样子的,而是要体现类的行为。理论上,既然sport不能准确体现Athlete类的行为,那么Athlete就不应该实现sport接口。而是应该实现没有jump()行为的接口,比如,把sport接口一分为二:interface Runnable {
      void run();
    }
    interface Jumpable {
      void jump();
    }
    interface sport extends Runnable, Jumpable {
    }再让Athlete去实现Runnable,就可以了。但实际上,你常常无法改变接口的定义。这种情况下,如果有你不想实现的方法,解决方法是抛出UnsupportedOperationException异常,表示该操作不被支持,如:
    class Athlete implements sport {
        public void run() {
            System.out.println("run");
        }
        public void jump() {
            throw new UnsupportedOperationException();
        }    
        public static void main(String [] args) {
            Athlete zhang = new Athlete();
            zhang.run();
            zhang.jump();  // 运行时抛出异常
        }
    }
      

  4.   

    若果你不想实现全部的接口 那可以用adapter来写啊 用一个中间的代理 呵呵
      

  5.   

    既然用接口,就必须实现接口的方法
    http://www.10zhizui.cn
      

  6.   

    //那就别用接口,用抽象类吧:abstract class sport
    {
       abstract void run();    void jump()
        {
        
        }
    }
    class Athlete extends sport
    {
        public void run()
        {
            System.out.println("run");
        }
        /*public void jump()
        {
            System.out.println("jump");
        }*/
        
        public static void main(String [] args)
        {
         Athlete zhang = new Athlete();
            zhang.run();
            zhang.jump();
        }
    }
      

  7.   

    interface sport
    {
        void run();
        void jump();
    }abstract   class   AbstractAthlete implements sport{{ 
          abstract   void   run();         void   jump() 
            { 
            
            } 

    class   Athlete   extends   AbstractAthlete 

            public   void   run() 
            { 
                    System.out.println("run"); 
            } 
      
            public   static   void   main(String   []   args) 
            { 
            Athlete   zhang   =   new   Athlete(); 
                    zhang.run(); 
                    zhang.jump(); 
            } 
    }