Reputation: 2472
SITUATION: Say there is a class A and an interface B.
REQUIREMENT: If any class, say C, wants to create objects of A and use them, then that class will also have to implement interface B.Is there any way to enforce this condition?
WHY: Now a question may arise as to why I want to do such a thing. The reason is that when a class C creates objects of A and uses them, then those objects call certain methods of C. I want to declare those methods in interface B, so that C will invariably implement those methods.
Upvotes: 0
Views: 1064
Reputation: 24732
Since you say that objects of class A
will call methods on C
, they will have to keep reference to C
somehow. Make this reference of type B
and you are done.
That is
public class A {
public A(B arg) {
....
}
}
Then in C
:
A a = new A(this);
That will force class C to implement interface B
.
Upvotes: 0
Reputation: 63708
Try this snippet:
public interface B {
// methods
}
public class A {
private final B b;
public A(B b) {
this.b = b;
}
...
}
public class C implements B{
// implement B's methods
public static void main(String[] arg) {
C c = new C();
A a = new A(c);
}
}
Upvotes: 1