me.at.coding
me.at.coding

Reputation: 17604

Ensure that an object is always member of a List?

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           
}

Upvotes: 0

Views: 77

Answers (2)

JimmyB
JimmyB

Reputation: 12610

Maybe make Character an private inner class of Word and add a method like addCharacter(String character) to Word?

Yes. - Or maybe only declare the constructor of MyCharacter private and the MyCharacter class final. Or declare the MyCharacter class outside of Word having a 'package-private' constructor. Or have a kind of (static) factory method inside MyCharacter like appendToWord( Word w, Character char ) and a private constructor. Or ... :-)

Edit: I first misunderstood the question:

would it be possible to let Word extend the List class with the private inner Character class?

Word can extend List<T> in any way. But -as you figured out- not List<Word.SomeInnerClass>.

Upvotes: 1

CapnSmack
CapnSmack

Reputation: 232

This is possible, in theory. One problem will arise in that Character is already a java class. Also, if you're using Eclipse, it won't let you declare

public class Word extends ArrayList<Letter> {
    private class Letter {
        //...
    }
}

unless you make Letter at most protected. I'm not sure whether that's an Eclipse issue or if Java would also stop you.

Regarding your superclass problem, it's because you cannot use List as it is only an interface. You must use something that implements it, like ArrayList.

Upvotes: 1

Related Questions