How to call create a proper interface
I have an interface with two methods
interface IFoo{
void FooOne(A,B,C);
void FooTwo(D,E,F);
}
Now there are two implementation class which extends this interface. One is as follows:
class Foo1 implements IFoo{
void FooOne(A,B,C);
void FooTwo(D,E,F);
}
Other one is as follows :
class Foo2 implements IFoo{
void FooOne(A,B,C);
void FooTwo(D,E,F);
}
Now Foo2 class dosen't needs parameter E at all. Parameter E is only required for class FOO1. So it's somehow ambious why this parameter is passed to class Foo2. So is there some another way so that I can do something like for cl开发者_如何学Goass Foo2.
class Foo2 implements IFoo{
void FooOne(A,B,C);
void FooTwo(D,F);
}
If Foo2
doesn't care about E
, it should simply ignore it. You can't change the signature of FooTwo
in a class that implements that interface, it doesn't make sens. The callers of IFoo.FooTwo
must not be aware of the actual class that implements it.
If FooTwo(D,E,F)
is your interface, then class Foo2 must implement that.
However, you could expose another non-interface overloaded public method for Foo2, like this
public void FooTwo(D,F) {
this(D, null, F);
}
There is no syntactic way to do that. You have to refactor your classes.
Answer following questions to get a proper refactoring:
- Why isn't parameter E required in some cases?
- What does Foo2 have in common with Foo1?
- Why do they need the same interface?
If Foo2 does not need parameter E at all, you have designed your interface incorrectly. In an interface, you should only be requiring those methods and parameters that are implementation independent. This is because you are abstracting your implementation from the users of your interface and they should not need to care if it is Foo1 or Foo2 that is the actual implementation.
First, a class cannot extend
an interface in java. So the code
class Foo1 extends IFoo{
when IFoo is an interface does not compile.
Assuming that you really meant implements
:
When you have an interface, you define a contract, a skeleton. All the classes that implement this interface have to follow this contract. See How interfaces are actually used
The interface should be general, and everything that is specified in the interface should be applicable to all classes that implement it. So
Now Foo2 class dosen't needs parameter E at al
questions the design of the interface.
You still can have another method in Foo2 that takes only two parameters D anf F if need be.
精彩评论