Imagine the following:
Every word is a list of characters. However there can be no character itself, it always has to be part of a word.
So the Word class could look like this:
class Word extends List<MyCharacter>
Now, how could one enforce that it isn't possible to instantiate a MyCharacter
which is not part of a Word
? Maybe make MyCharacter
an private inner class of Word
and add a method like addCharacter(String character)
to Word
? But then, would it be possible to let Word
extend the List class while MyCharacter
is a private inner class of Word
?
Thanks for any hint on this!
Update:
I now ended up at
import java.util.ArrayList;
public final class Word extends ArrayList<Word.MyCharacter> {
protected final class MyCharacter
{
private String character;
public String getCharacter() {
return character;
}
public MyCharacter(String character)
{
this.character=character;
}
}
public void addCharacter(String character) {
add(new MyCharacter(character));
}
}
And here is how it's used:
public static void main(String[] args) {
Word word = new Word();
// word.add(new MyCharacter("a")); // as intended: not possible, because MyCharacter class can't be accessed
word.addCharacter("a"); // ok
}