I am trying to understand this recursive interface definition in apache thrift source code
public interface TBase<T extends TBase<?, ?>, F extends TFieldIdEnum> extends Comparable<T>, Serializable {
From my understanding TBase is a interface containing type parameter T and F.
T has the constraint that it also have to be extending TBase that has type parameter containing any type.
What I am confused about is what is the terminating TBase
Say I have
public class TBaseImpl<A, B> implements TBase<A, B>
A has to be a TBase
so there must be another class implement A
public class TBaseImplA<C, D> implements TBase<C, D>
but C have to be a TBase
so there must be another class implement C
This goes on forever.
So my question is
What is terminating condition for TBase
What is the benefit of this recursive definition?
Can someone point me a direction?
Thanks
so there must be another class implement A
That is not necessarily true. With this type of recursive bounds, there are 2 possible ways to satisfy the constraint when creating a subtype.
Declare your own type parameter with the same or more restrictive bounds. This places the burden of choosing the type parameter on the user of this class.
public class TBaseImpl<A extends TBase<A, B>, B extends TFieldIdEnum> implements TBase<A, B>
or more likely
public class TBaseImpl<A extends TBaseImpl<A, B>, B extends TFieldIdEnum> implements TBase<A, B>
Pass the same class as what you're defining to satisfy the original bound.
public class TBaseImpl<B extends TFieldIdEnum> implements TBase<TBaseImpl, B>
A benefit of this pattern is being able to restrict the parameter of a method that is meant to take in another instance of the same class, e.g.:
public void example(T other)
This is (in Java) the Curiously Repeating Template Pattern.
Normally an implementing/overriding method must match the parameter types and order of parameters exactly. But this pattern allows you to narrow the type by narrowing the type parameter. E.g. such a method in TBaseImpl in this case would only take a TBaseImpl and not the broader T or TBase. In such a class there is a relationship between the class and itself.
Another benefit is method chaining, in which a method returns this to allow
obj.method1().method2().method3()
In this way, chaining methods can be declared to return T, so that e.g. a TBase<TBaseImpl> variable can call these methods, each returning a TBaseImpl on which another method can be called.
T method1(); // in TBase
#Override
TBaseImpl method1(); // in TBaseImpl
Incidentally, if you're trying to declare a type variable that is a subtype of an enum, that's not necessary because an enum is final and cannot be extended. It would be simpler to remove F in the interface and have implementing classes use the enum directly.
Related
For example, I want to create a generic interface IEnum and make sure that every IEnum instance is also an enum constant, in other words, only enum type can implement IEnum. Does java support such feature or can it be achieved by any workaround? Can it be achieved by recursive Bounded Type Parameters?
You can use a recursive bounded and a union type parameter, to enforce that the the passed generic class is an Enum and implements IEnum:
public interface IEnum<E extends Enum<E> & IEnum<E>> {}
Note: the order matters, so the first type can either be a class or interface, but everything that follows it must be an interface.
You can then use it like this:
public enum Foo implements IEnum<Foo> {}
Sadly, you can't force the implementing class to pass itself as a type parameter, e.g. this would work:
public class Bar implements IEnum<Foo> {}
Also you can't constrain the implementation to not use raw types, e.g. this would also work:
public class Baz implements IEnum {}
Is there a special reason in Java for using always "extends" rather than "implements" for defining bounds of type parameters?
For example:
public interface C {}
public class A<B implements C>{}
is prohibited, but
public class A<B extends C>{}
is correct. What is the reason for that?
There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).
The answer is in here :
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean either extends (as in classes) or implements (as in interfaces).
So there you have it, it's a bit confusing, and Oracle knows it.
Probably because for both sides (B and C) only the type is relevant, not the implementation.
In your example
public class A<B extends C>{}
B can be an interface as well. "extends" is used to define sub-interfaces as well as sub-classes.
interface IntfSub extends IntfSuper {}
class ClzSub extends ClzSuper {}
I usually think of 'Sub extends Super' as 'Sub is like Super, but with additional capabilities', and 'Clz implements Intf' as 'Clz is a realization of Intf'. In your example, this would match: B is like C, but with additional capabilities. The capabilities are relevant here, not the realization.
Here is a more involved example of where extends is allowed and possibly what you want:
public class A<T1 extends Comparable<T1>>
It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:
class MyGen<T, U extends T> {
Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.
It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.
But I think implements would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.
The Java Glossary expresses a similar view.
We are used to
class ClassTypeA implements InterfaceTypeA {}
class ClassTypeB extends ClassTypeA {}
and any slight deviation from these rules greatly confuses us.
The syntax of a type bound is defined as
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}
(JLS 12 > 4.4. Type Variables > TypeBound)
If we were to change it, we would surely add the implements case
TypeBound:
extends TypeVariable
extends ClassType {AdditionalBound}
implements InterfaceType {AdditionalBound}
and end up with two identically processed clauses
ClassOrInterfaceType:
ClassType
InterfaceType
(JLS 12 > 4.3. Reference Types and Values > ClassOrInterfaceType)
except we would also need to take care of implements, which would complicate things further.
I believe it's the main reason why extends ClassOrInterfaceType is used instead of extends ClassType and implements InterfaceType - to keep things simple within the complicated concept. The problem is we don't have the right word to cover both extends and implements and we definitely don't want to introduce one.
<T is ClassTypeA>
<T is InterfaceTypeA>
Although extends brings some mess when it goes along with an interface, it's a broader term and it can be used to describe both cases. Try to tune your mind to the concept of extending a type (not extending a class, not implementing an interface). You restrict a type parameter by another type and it doesn't matter what that type actually is. It only matters that it's its upper bound and it's its supertype.
In fact, when using generic on interface, the keyword is also extends. Here is the code example:
There are 2 classes that implements the Greeting interface:
interface Greeting {
void sayHello();
}
class Dog implements Greeting {
#Override
public void sayHello() {
System.out.println("Greeting from Dog: Hello ");
}
}
class Cat implements Greeting {
#Override
public void sayHello() {
System.out.println("Greeting from Cat: Hello ");
}
}
And the test code:
#Test
public void testGeneric() {
Collection<? extends Greeting> animals;
List<Dog> dogs = Arrays.asList(new Dog(), new Dog(), new Dog());
List<Cat> cats = Arrays.asList(new Cat(), new Cat(), new Cat());
animals = dogs;
for(Greeting g: animals) g.sayHello();
animals = cats;
for(Greeting g: animals) g.sayHello();
}
Using “extends” in <T extends Comparable> is a promise that the data type will either itself directly implement Comparable, or else will extend a class implementing Comparable. You might have written a subclass B of another class A that implements Comparable, and if you declare your data type <T extends Comparable>, then you may use either A or B as your data type when instantiating the class.
I don't understand why Company compiled. I thought it checked for extends but not for implements?
public interface Employee
public class HourlyEmployee implements Employee
public class Company<T extends Employee>
Company<HourlyEmployee> company = new Company<>();
The extends keyword in Generics has a slightly different semantics than the general extends keyword.
When using extends in the context of Generics, for example T extends Something, this means that T should be a type that either implements the interface Something (in cases when Something is interface), or is a subclass of Something (in case Something is a class).
Probably the reason for this is that if the implements keyword was supported in Generics, this would have made type-parameter declaration too verbose.
For example, you'd have:
<T extends SomeClass implements Serializable & Observable>
Instead, the valid syntax for this would be:
<T extends SomeClass & Serializable & Observable>
And you don't need to have the implements keyword, actually. When defining the bounds of a type T, you just need to point out which types does your type T derive from, without caring if those are interfaces or classes.
The type definition is not a class definition. You can consider type definition as joining few data sets, where the resulting set is your type T.
The notation T extends Employee in the declaration of a type parameter refers to either extending a class or implementing an interface.
public class Company<T implements Employee> is not a valid syntax.
Therefore public class Company<T extends Employee> means that the generic type parameter T of your Company class must implement the Employee interface.
I have a class with a bounded type parameter with nested wildcard bounded types. In the class I need to use the types of the bound nested parameters in multiple methods. Is there a way to define the wildcard bounded type as a generic type parameter instead or assign it to a generic variable name so that it can easily be referenced in multiple places?
The way the class is implemented now is like
class AbstractManager<F extends Filter<? extends Criteria<? extends Type>>>
{
protected void setFilter(F filter)
{
setCriteria(f.getCriteria());
}
protected <T extends Criteria<? extends Type>> void setCriteria(List<T> criteria)
{
}
protected <T extends Criteria<? extends Type>> void doSomethingWithCriteria(List<T> criteria)
{
...
}
}
which does not bound actually restrict the type of the list to the type of the Filter but is good enough in our situation. Ideally the type of the list would be restricted to the type of the filter using a construct that could bind the inferred type of the filter to a name much like a bounded type parameter on a method but at the class level instead.
Basically I would like to do something like
class <G extends Criteria<? extends Type> AbstractManager<F extends Filter<G>>
From what I know and can find, this is not possible, but I was hoping that maybe there was an obscure feature or new feature in java 7 that would make this possible.
I know it is possible to specify a second type parameter like
class AbstractManager<F extends Filter<G>, G extends Criteria<? extends Type>>
but I do not want the child classes to have to specify G when the compiler can determine it.
The only possible option/solution I have been able to find is to have a shallow subclass with factory methods given in the solution to this question
Nested Type Parameters in Java
and in
Java generics - use same wildcard multiple times
If I understand what you intend to do, it would change the semantics of your class.
Right now in your current class, you could have for example:
class T1 extends Type {}
class T2 extends Type {}
class C1 extends Criteria<T1> {}
class C2 extends Criteria<T2> {}
class C3 extends Criteria<T2> {}
class F1 extends Filter<C1> {}
class Manager extends AbstractManager<F1> {}
And then, even though Manager is based on F1, some user code would be perfectly legal if it did:
Manager m = new Manager();
C2 c2 = new C2();
C3 c3 = new C3();
m.setCriteria(Arrays.asList(new C2[]{c2});
m.doSomethingWithCriteria(Arrays.asList(new C3[]{c3});
I don't know if it was your intent, but it is legal (from a compiler point of view). However, if you were somehow able to name that wildcard type, by using that name in your methods you would constrain the user of your class to use the same type in all methods. In other words, in my example the methods would have to be called with lists of C1.
As a conclusion, if you want the flexibility that your example has, you need to repeat the wildcard; but if you want a constraint that the methods use the same criteria as the filter of the manager, then you actually gave the solution:
class AbstractManager<F extends Filter<G>, G extends Criteria<? extends Type>>
(or create a dedicated sub-type to avoid the repeating, as you mentioned (anything that you don't like with that?))
I encountered the following piece of a definition for a generic class:
public class binarysearchnode<T extends Comparable<T>> implements Comparable<binarysearchnode<T>>{
.............
}
Please help explaining why a class would specify itself as a Type parameter to comparable while implementing the comparable interface?
How would it be different from the following:
public class binarysearchnode<T extends Comparable<T>> implements Comparable<? super (or extends)T>{
.............
}
This makes it possible to compare binarysearchnodes to each other. If it implemented Comparable<T>, that would instead mean that the node could be compared to the value of the node, which would be odd.
Inside the class you will probably find something like this:
T value;
public int compareTo(binarysearchnode<T> other) {
return value.compareTo(other.value);
}
In order to be able to implement compareTo() like this, the value class (T) needs to be comparable to other objects of its class - hence the declaration of <T extends Comparable<T>> in the class definition.
It is because what the class author wants is to be able to write:
b1.compareTo(b2)
where b1 and b2 are binarysearchnode instances. The developer also adds a constraint to T so that T extends Comparable<T>. Probably so that the implementation of Comparable for binarysearchnode can just rely on T instances being Comparable themselves.
More generally, while it is possible for a class C1 to implement Comparable<C2>, ultimately, it makes no sense to do so: this does not mean that an instance of C2 could be comparable to an instance of C1. And due to type erasure, it would not be possible, for instance, for class C1 to implement both Comparable<C1> and Comparable<C2>.
Also, if binarysearchnode<T> were to implement Comparable<T> directly, you would have at least two problems:
you would not be able to compare one binarysearchnode<T> to another;
given a binarysearchnote<T> instance b and a T instance t, you would be able to write b.compareTo(t) but not t.compareTo(b) (since T does not, and cannot, implement Comparable<binarysearchnode<T>>), and that breaks the Comparable contract.
Let's say you have a superclass A and a subclass B. Imagine the superclass implements Comparable<A>, then B will also implement Comparable<A> through inheritance.
Your binarysearchnode class declared as such :
public class binarysearchnode<T extends Comparable<T>>
will not be able to take B as a type parameter for T (B does not implement Comparable<B>)
But when defined as such :
public class binarysearchnode<T extends Comparable<? super T>>
it will be able to take B as a type parameter for T, since B implements Comparable<A> which fulfills Comparable<? super T>.