有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java接口方法可以重载吗?

我试图实现一个重载接口方法。我知道这在Java中不起作用,但我如何重写以下内容,使action()方法中有实现类型,而不是Base类型

class Base;
class Foo extends Base;
class Bar extends Base;

interface IService {
   void action(Base base);
}

class FooService implements IService {
   void action(Foo foo) {
     //executes specific foo action
   }
}

class BarService implements IService {
   void action(Bar bar) {
     //executes specific Bar action
   }
}

用法:

Base base; //may be foo or bar
anyService.action(bar);

你明白了。我怎么能这样做


共 (5) 个答案

  1. # 1 楼答案

    您始终可以将类型转换为特定类型以执行该操作

    void action(Base base) 
    {
        if(base instanceof Foo)
        {
             Foo foo = (Foo) base;
             //executes specific foo action
        }
        else
        {
            // handle the edge case where the wrong type was sent to you
        } 
    }
    
  2. # 2 楼答案

    定义一个FooBar都应该实现的接口,这样您就可以执行以下操作:

    interface Actionable{
        public void action;
    }
    
    class Base;
    class Foo extends Base implements Actionable;
    class Bar extends Base implements Actionable;
    
    interface IService {
       void action(Actionable a);
    }
    
    class FooService implements IService {
       void action(Actionable a) {
        ...
       }
    }
    
    class BarService implements IService {
       void action(Actionable a) {
        ...
       }
    }
    

    无论如何,接口应该使代码更加健壮和可重用——如果你正在查看黑客以使它们工作,请考虑更好地设计应用程序。

  3. # 3 楼答案

    这在Java中不受支持,并且您违反了OOP规则

  4. # 4 楼答案

    根据您的预期用途,可以尝试多种方法

    如果您对iSeries设备的调用知道它们可以接受哪种类型的对象,您可以尝试使用泛型

    interface IService<T extends Base> {
       void action(T foo)
    }
    

    使用方法:

    IService<Foo> fooService = ...
    fooService.action(fooObject);
    

    如果不是这样的话,您可以在“基类”中进行一些检查,以便区分iSeries接口

    class Base {
       boolean acceptsFoo();
       boolean acceptsBar();
    }
    

    你可以像这样使用它:

    class AnyService implements IService {
       void action(Base base) {
         if (base.acceptsFoo()) {
            ((FooService) base).foo();
         }
    }
    

    然而,这似乎是一个奇怪的设计。接口旨在提供统一的访问,如果您需要区分参数,这几乎总是一个接口可以分成几个部分的标志

  5. # 5 楼答案

    如果您正在传递子类的对象,任何方式都可以

    然后将调用传递的对象(子类)(多态性)的行为(实例方法)

    即重载方法