Interface hierarchy - java

I have a problem with interface hierarchy. My projects has four class and six interface in a rigid structure, that is:
public interface Set<T, N extends Settable<T,N>>
public interface Settable<T, N>
public interface Sequence<T, N extends Sequenceable<T,N>> extends Set<T,N>
public interface Sequenceable<T,N> extends Settable<T,N>
public interface DisjoinedSet<T, N extends DisjoinedSettable<T,N>> extends Set<T,N>
public interface DisjoinedSettable<T,N> extends Settable<T,N>
public class List<T> implements Sequence<T, NodeList<T>>
public class NodeList<T> implements Sequenceable<T,NodeList<T>>
public class ListDisjoined<T> extends List<T> implements DisjoinedSet<T,NodeListDisjoined<T>>, Sequence<T,NodeListDisjoined<T>>
public class NodeListDisjoined<T> extends List<T> implements DisjoinedSettable<T,NodeListDisjoined<T>>, Sequenceable<T,NodeListDisjoined<T>>
Beside the horrible naming, the idea is that by creating container-contained couples of classes/interfaces I gain an enormous amount of sinergy: I can simply write the body of those methods inside the comments of the interfaces and copy&past on a whole brunch of classes, without changing anyting.
However, I got two errors on the last two class:
The interface Sequence cannot be implemented more than once with different arguments: Sequence<T,NodeList<T>> and Sequence<T,NodeListDisjoined<T>>
The interface Sequenceable cannot be implemented more than once with different arguments: Sequenceable<T,NodeList<T>> and Sequenceable<T,NodeListDisjoined<T>>
NodeListDisjoined is a subclass of NodeList, so what is the problem?
Note: the edit written under this line works. I still do not understand why.
public interface DisjoinedSet<T, N extends DisjoinedSettable<T,N>> extends Sequence<T,N>
public interface DisjoinedSettable<T,N> extends Sequenceable<T,N>

Related

How make a generic type in java?

I want make my List. But I dont know how to write generic type in java.
public interface myListInt <E extends Comparable<E>>{}
public class myList<E extends myListInt<E>> extends LinkedList{}
When I am doing that, it gives an error.How should ı write.
The exact intent of your code is unclear, but I got an error for the <E> in myListInt<E>.
public interface myListInt <E extends Comparable<E>>{}
public class myList<E extends myListInt<E>> extends LinkedList{}
^ Error here
This is because you need to constrain E to extend Comparable<E> in order to be a valid bound for myListInt<E>:
public class myList<E extends Comparable<E> & myListInt<E>>
extends LinkedList{}
However, you maybe also want to add a constraint to LinkedList too (assuming this is java.util.LinkedList:
public class myList<E extends Comparable<E> & myListInt<E>>
extends LinkedList<E> {}

Is it possible to extend a generic class while restricting the generic type?

Suppose I have abstract classes (or, indeed, interfaces)
public abstract class Animal
public abstract class Bird Extends Animal
and a generic class
public class Lifestyle<A extends Animal>
So we might create a Lifestyle<Lion> object.
The Lifestyle class contains methods that animals can use to tell them how to walk around, find food, interact with other animals of the same species, etc. Now suppose I want to extend this class to a special BirdLifestyle class that tells Birds how to do all the above things, but also tells them how to fly and use all of the extra methods in the Bird class. I want to be able to create a BirdLifestyle<Eagle> object, for instance. I'm pretty sure that the following won't compile:
public class BirdLifestyle<B extends Bird> extends Lifestyle<A extends Animal>
and the only alternative I can think of is rather nasty:
public class BirdLifestyle<B extends Bird>
{
private Lifestyle<B> lifestyle // tells the bird how to do animal things.
public Lifestyle<B> getLifestyle()
{
return lifestyle;
}
// Bird-specific methods.
}
We could then get all of the methods from Animal by calling getLifestyle().walk() or things like that.
Now suppose that my friends have all created their own implementations of these four classes and that we want to link them using interfaces. So we create
public interface LifestyleInterface
{
public void walk();
// etc.
}
public interface AvianLifestyleInterface extends LifestyleInterface
{
public void fly();
// etc.
}
My friends are all more specialize, so they've all written things like:
public class LionLifestyle implements LifestyleInterface
or
public class EagleLifestyle implements AvianLifestyleInterface
while I can write:
public class Lifestyle<A extends Animal> implements LifestyleInterface
But I can't now write:
public class BirdLifestyle<B extends Bird> implements AvianLifestyleInterface
even if my BirdLifestyle class overrides all the methods introduced in AvianLifestyleInterface. This is because BirdLifestyle is not a superclass of Lifestyle. The only way round this is to create lots of entry-point methods such as:
public class BirdLifestyle<B extends Bird>
{
private Lifestyle<B> lifestyle;
public Lifestyle<B> getLifestyle()
{
return lifestyle;
}
// 'AvianLifestyleInterface' methods.
#Override
public void fly()
{
// Code for flying.
}
// etc.
// 'LifestyleInterface' methods.
#Override
public void walk()
{
getLifestyle().walk();
}
// etc., creating a similar one-line method for each method in
// 'LifestyleInterface' that is just an entry-point to the same
// method in the 'Lifestyle<A>' object.
}
This seems like an unnecessary amount of code to write, and a lot of the code is written in a fairly mechanical way, which breaks several programming rules. For example, if I want to add any methods to the LifestyleInterface interface then I need to remember to add a new one-line method into the BirdLifestyle class. Is there a cleaner way?
It's a little unclear to me what you are really asking here, but it seems that your first attempt can be easily remedied by:
public class BirdLifestyle<B extends Bird> extends Lifestyle<B> {
// ...
}
Lifestyle is already declared to be generic as Lifestyle<A extends Animal>, no need to repeat what the generic type bound is (and as you say, it won't compile).
Similarly:
public class BirdLifestyle<B extends Bird> extends Lifestyle<B> implements AvianLifestyleInterface {
// ...
}
Will work.
I'm pretty much lost in your question right now. But you can surely change your BirdLifestyle class to:
public class BirdLifestyle extends Lifestyle<Bird> { }
Don't see why you would make BirdLifestyle itself a generic class here. Will update the answer if I understand other part of the question.
If you're moving to interfaces, then you can just do:
public class BirdLifestyle implements AvianLifestyleInterface { }
Again, why would you make the class generic? The name BirdLifeStyle should really describe the life style of a bird. Do you have different kinds of Bird?

Linear inheritance structure not working b/c of root interface: Copyable<C extends Copyable<C>>

(This is a follow up to this question, which itself was a follow up to this question.)
I have the following interfaces/classes (skeleton code below)
interface Copyable<C extends Copyable<C>> {
interface Validator<V extends Validator<V>> extends Copyable<V> {
interface ValidateValue<O> extends Validator<ValidateValue<O>> {
abstract class AbstractValidator<V extends AbstractValidator<V>> implements Validator<V> {
class VVNull<O> extends AbstractValidator<VVNull<O>> implements ValidateValue<O> {
This used to work just grand when Copyable was implemented without the <C extends Copyable<C>> but, as the two previous questions make clear to me, Copyable really needs those generics.
Unfortunately, now I can't compile VVNull.
C:\java_code\CopyableCProblem.java:23: error: Validator cannot be inherited with different arguments: <ValidateValue<O>> and <VVNull<O>>
This is line 23 in the below source-code:
class VVNull<O> extends AbstractValidator<VVNull<O>> implements ValidateValue<O> {
VVNull<O> is a ValidateValue<O>. It passes itself up as a generic-parameter for goodness-sakes, and it implements ValidateValue<O>. The inheritance is completely linear--there's no "diamond" inheritance or anything, it's Copyable<--Validator<--ValidateValue<--VVNull.
I realize--or actually, I should say I think--that self-generics will work, that is, if you make every class self-genericized, such as
VVNull<O,V extends VVNull<O,V>>
but I am desperate to find another solution. Self-referential generics are a complete mess when you get down to sub-classes that need their own additional generics. That's why I only self-genericize through Validator, because it's the least-likely candidate to be directly used. ValidateValue and VVNull are frequently and directly used. I really really hope that there are other possibilites.
Comparable works just fine without requiring self-generics in all its implementing classes, so how can I make this work for Copyable?
Thank you for any advice.
public class CopyableCProblem {
}
interface Copyable<C extends Copyable<C>> {
C getObjectCopy();
}
interface Validator<V extends Validator<V>> extends Copyable<V> {
}
interface ValidateValue<O> extends Validator<ValidateValue<O>> {
#Override
ValidateValue<O> getObjectCopy();
boolean isValid(O o_o);
}
abstract class AbstractValidator<V extends AbstractValidator<V>> implements Validator<V> {
}
class VVNull<O> extends AbstractValidator<VVNull<O>> implements ValidateValue<O> {
#Override
public VVNull<O> getObjectCopy() {
return this;
}
public boolean isValid(O o_o) {
return (o_o != null);
}
}

Force children to use enums defined within themselves

Let's say I've got a parent abstract animal trainer class:
public abstract class Trainer
<A extends Animal,
E extends Enum<E> & Trainables>{
protected EnumSet<E> completed;
public void trainingComplete(E trainable){
trainingComplete.add(trainable);
}
I want concrete extensions of the parent animal trainer to complete training for only the trainables defined by it. So if I have a concrete Dog Trainer as follows:
public class DogTrainer extends Trainer<Dog, DogTrainer.Tricks>{
public enum Tricks implements Trainables {
FETCH, GROWL, SIT, HEEL;
}
}
With the current definition of DogTrainer I can only do trainingComplete for parameters of the DogTrainer.Tricks type. But I want to enforce that anyone who creates a concrete Trainer should allow trainingComplete() for Trainables that it defines within itself.
In other words, the problem with my current design is, if I had another trainer as follows:
public class PoliceDogTrainer extends Trainer<Dog, PoliceDogTrainer.Tricks>{
public enum Tricks implements Trainables {
FIND_DRUGS, FIND_BOMB, FIND_BODY;
}
}
There is nothing preventing someone from defining another rouge trainer that tries to teach the dog, police tricks:
public class RougeTrainer extends Trainer<Dog, PoliceDogTrainer.Tricks>{
...
}
I want to prohibit this and allow extending class to use ONLY Trainables they themselves specify.
How can I do that?
You can make the enums non-public but that cannot be enforced by the abstract base class. An alternative is to make Trainables generic by adding a type parameter which must match the Trainer class. This does not enforce the enum to be an inner class (that’s impossible) but for a conforming sub class, no RogueTrainer can be created then.
Enforcing constraints on the type of this inside the base class or interface lies somewhere between tricky and impossible. One commonly known example is the Comparable interface which cannot be declared in a way to prevent implementations like class Foo implements Comparable<String>.
One way to circumvent this problem is to make the Trainer reference a parameter, e.g.
public interface Trainables<T extends Trainer<?,? extends Trainables<T>>>
…
public abstract class Trainer
<A extends Animal,
E extends Enum<E> & Trainables<? extends Trainer<A,E>>> {
protected EnumSet<E> completed;
void trainingCompleteImpl(E trainable) {
completed.add(trainable);
}
public static <A extends Animal, T extends Trainer<A,E>,
E extends Enum<E> & Trainables<T>> void trainingComplete(T t, E trainable) {
t.trainingCompleteImpl(trainable);
}
}
public class PoliceDogTrainer
extends Trainer<Dog, PoliceDogTrainer.Tricks> {
public enum Tricks implements Trainables<PoliceDogTrainer> {
FIND_DRUGS, FIND_BOMB, FIND_BODY;
}
}
The public static method can only be invoked with the right combination of Trainer and Trainables. The trainingCompleteImpl method can be invoked and overridden by trusted subclasses within the same package. If you don’t want this you can inline the code of the method and remove the instance method completely.
_
An alternative is to create a type parameter for the Trainer and enforce a match between the parameter and this at runtime:
public interface Trainables<T extends Trainer<?,T,? extends Trainables<T>>>
…
public abstract class Trainer
<A extends Animal, T extends Trainer<A,T,E>,
E extends Enum<E> & Trainables<T>> {
protected EnumSet<E> completed;
/** sub-classes should implements this as {#code return this}*/
protected abstract T selfReference();
void trainingComplete(E trainable) {
if(selfReference()!=this) throw new IllegalStateException();
completed.add(trainable);
}
}
public class PoliceDogTrainer
extends Trainer<Dog, PoliceDogTrainer, PoliceDogTrainer.Tricks> {
public enum Tricks implements Trainables<PoliceDogTrainer> {
FIND_DRUGS, FIND_BOMB, FIND_BODY;
}
#Override
protected final PoliceDogTrainer selfReference()
{
return this;
}
}
So, for a non-conforming Trainer implementation selfReference() cannot be implemented as return this; which can be detected easily. For a conforming implementation the JVM will inline the selfReference method and see this==this then which will be optimized away; so this check has no performance impact.

Usage of extends in Class, Abstract, Interface combination

My main question revolves around when to use and what is the difference between the following when combined with Class, Abstract, Interface:
<E>
<E extends Interface>
<? extends Interface>
Shown below is a detailed question with some code signatures:
This code uses Guava Forwarding Decorators to define specific collections.
Base Interface:
public interface AnimalSetInterface<E extends AnimalI> extends Set<E>
This works:
public interface AsiaI<E extends AnimalI> extends AnimalSetInterface<E>
The following gives an error:
public interface AsiaI<E> extends AnimalSetInterface<E>
Bound mismatch: The type E is not a valid substitute for the bounded
parameter of the type AnimalSetInterface
What I am trying to understand is if I have specified at the Base Interface that I only want <E extends AnimalI> then why do I have to specify again in AsiaI?
I am trying to understand generics and at the same time minimize code.
Also if both classes have such code is there a good way to combine/minimize (remove/generify boilerplate code) it:
Asia:
public Asia(final ImmutableSet<E> animalSet){
super(animalSet);
}
public static <E extends AnimalI> AsiaI<E> of(final ImmutableSet<E> animalSet){
return new Asia(animalSet);
}
Africa:
public Africa(final ImmutableSet<E> animalSet){
super(animalSet);
}
public static <E extends AnimalI> AfricaI<E> of(final ImmutableSet<E> animalSet){
return new Africa(animalSet);
}
public class Africa<E extends AnimalI> extends AnimalSetAbstract implements AfricaI
public class Asia<E> extends AnimalSetAbstract implements AsiaI
The difference is that in the first case, your generic type must extend AnimalI
In the second case, your generic type could be any class.

Categories

Resources