简体   繁体   中英

Can interface methods be overloaded?

I'm trying to achieve an overloaded interface method. I know that this does not work in Java, but how could I rewrite the following to have the implementation type in my action() methods, and not the Base type?

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
   }
}

usage:

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

You get the idea. How could I do this?

Java不支持此功能,并且您违反了OOP规则。

Depending on your intended usage, there are multiple things to try.

If your calls to the IService know which kinds of object they can take, you could try generics.

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

and usage:

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

If that's not the case, you could have some check in your ´Base´ class to allow differentiation for your IService interface.

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

and you could use it like:

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

However , this seems like a strange design. An interface is aimed at providing uniform access, and if you need to differentiate between the arguments, this is almost always a sign of an interface that can be split up into several parts...

Define an interface that both Foo and Bar should implement, so you can do like:

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) {
    ...
   }
}

Anyway interfaces should make your code more robust and reusable - if you are looking into hacks to make them work, consider designing your application better.

You can always typecast to a specific type to execute that action.

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
    } 
}

any way if you are passing objects of sub class

then behavior (instance methods) will be called of object(subclass) passed(polymorphism)

ie.overloaded method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM