Let's say I have an Interface 'Inter', and Inter has a method
Inter someMethod();
How can I specify that the type of the return object has to be the same as the object upon which the method is called?
So if I have two classes 'C1' and 'C2' that implement Inter, if an instance of C1 calls someMethod (c1.someMethod()
) the result will be an instance of C1, whereas if an instance of C2 calls someMethod the result will be an instance of C2.
How about parameters? If Inter has a second method
void someMethod2(Inter inter)
How can I specify that the parameter has to be an instance of the same class as the object calling the method?
Using Generics.
public interface Inter<T> {
T someMethod();
void someMethod2(T obj);
}
public class C1 implements Inter<C1> {
public C1 someMethod() {
// ..
}
public void someMethod2(C1 obj) {
// ..
}
}
public class C2 implements Inter<C2> {
public C2 someMethod() {
// ..
}
public void someMethod2(C2 obj) {
// ..
}
}
Reference :
Generic Types (The Java™ Tutorials > Generics)
Edit : (Using a bounded generic type; in response to OP's comments)
public interface Inter<T extends Inter<T>> {
T someMethod();
void someMethod2(T obj);
}
public class C1 implements Inter<C1> {
public C1 someMethod() {
return new C1();
}
public void someMethod2(C1 obj) {
// ..
}
}
public class C2 implements Inter<C3> { // ERROR
..
}
But, here comes the catch.
public class C2 implements Inter<C1> { // COMPILES!
..
}
Because, C1
also satisfies T extends Inter<T>
. This is as far as this can go I believe.
Reference :
Bounded Type Parameters (The Java™ Tutorials > Generics)
You can try something like this
public interface Inter<T> {
public T doSomething();
}
public class C1 implements Inter<C1> {
@Override
public C1 doSomething() {
return new C1();
}
}
public class C2 implements Inter<C2> {
@Override
public C2 doSomething() {
return new C2();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With