-1

I really love using initializers to make constructing and configuring classes more understandable. Basically I prefer this:

new ClassObj().StartingFrom(1).EndingAt(5).IncrementBy(1).Backwards();

Rather than this:

new ClassObj(1,5,1,false);

This is a bit of a pain in Java when mixed with inheritance, as returning types default to as generic as possible. I've found a workable solution using self-referential inheritance (Java: returning subclass in superclass method signature), but I'm having some problems with it.

My issue is that the Parent class implements Iterable, but the generic type parameter gets lost, so the for-each loop wants to return an Object instead of a File.

Here's an SSCCE showing the behavior:

public class SSCCE {
  private static abstract class Sentence<T extends Sentence<T>> implements Iterable<String> {
    protected LinkedList<String> Words = new LinkedList<>();

    abstract T self();

    public T Say(String word) {
      Words.add(word);
      return self();
    }

    @Override
    public Iterator<String> iterator () {
      return Words.iterator();
    }
  }

  static class QuietSentence extends Sentence<QuietSentence> {
    public QuietSentence Whisper(String word) {
      Say(word.toLowerCase());
      return this;
    }

    @Override
    QuietSentence self() {
      return this;
    }
  }

  static class LoudSentence extends Sentence<LoudSentence> {
    public LoudSentence Shout(String word) {
      return Say(word.toUpperCase());
    }

    @Override
    LoudSentence self() {
      return this;
    }
  }

  static void PrintWords(Sentence words) {
    for(Object obj : words) {
        // I'd really like to avoid this cast
        String word = (String)obj;
        System.out.println(new StringBuilder(word).append(": ").append(word.length())
                  .toString());
    }
  }

  public static void main (String[] args) {
    QuietSentence peaceful_words = new QuietSentence().Say("Hello").Whisper("World");
    PrintWords(peaceful_words);

    LoudSentence noisy_words = new LoudSentence().Say("Hello").Shout("World");
    PrintWords(noisy_words);
  }
}

What's going on, and how can I fix it?

13
  • you know that (T) this is an unsafe cast, right?
    – newacct
    Nov 13, 2014 at 0:32
  • Normally it would be. In this case T is known to be either of type Sentence or one of its subclasses, so it's safe make the cast.
    – Morgen
    Dec 18, 2014 at 22:49
  • Nope. It is not safe. yes, T is known to be a subtype of Sentence<T>, but Sentence<T> is not known to be a subtype of T.
    – newacct
    Dec 19, 2014 at 0:54
  • I'd be interested looking at an alternative solution to the base problem, if you've found something better. For the time being, the limited visibility and idiomatic usage make this a pretty safe 'unsafe' cast.
    – Morgen
    Jan 6, 2015 at 23:27
  • 1
    Oh I see that you moved the self() call to Sentence.Say(). If you must have it be an instance method, the only absolutely safe way to do it would be to make self() abstract: abstract T self();. And every subclass is responsible for overriding it with a method that returns T. Your QuietSentence and LoudSentence classes would just return this, and if somebody does SomeClass extends Sentennce<OtherClass>, then they will be responsible for implementing a method that returns some instance of OtherClass. In all cases, it is still type-safe.
    – newacct
    Jan 8, 2015 at 0:44

1 Answer 1

1

So it turns out the problem was that I was not specifying the type correctly. A minimal fix in the PrintWords function solves the problem.

static void PrintWords(Sentence<? extends Sentence> words) {
    for(String word : words) {
        System.out.println(new StringBuilder(word).append(": ").append(word.length())
                .toString());
    }
}
3
  • I voted u up, I was writing you missed the inheritance
    – eduyayo
    Nov 11, 2014 at 22:44
  • Sentence<?> would be more proper. Otherwise you've got a raw type in there still. But yes this is basically the solution, because using a raw Sentence causes the entire class to be erased (including the type of Iterable).
    – Radiodef
    Nov 11, 2014 at 22:52
  • In this case, I believe that <? extends Sentence> is more correct because, it retains type safety. The more specific generic restricts references to Sentence and its subtypes.
    – Morgen
    Dec 18, 2014 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.