This needs a different approach
Saaa
empty at needmail.com
Wed Apr 30 09:39:17 PDT 2008
>
>>
>>> >
>>>> IFruit[] fruits = [APPLE, PLUM, APPLE ... PEAR, PLUM];
>>>>
>>>> Since all fruits inherit from IFruit, they can all be represented as
>>>> IFruit references. So, if you have an array of IFruit, you can put all
>>>> different kinds of fruits in it.
>>>
>>> Calling 'fruit[2].eat();' would call eat() from that specific APPLE,
>>> right?
>>
>>Changing fruit[2] to PLUM would go how?
>
> Just assign as normal, fruits[2] = PLUM.
>
> [CODE]
> import std.stdio;
>
> interface IFruit
> {
> void eat();
> }
>
> IFruit APPLE;
> IFruit PEAR;
> IFruit PLUM;
>
> static this()
> {
> APPLE = new class() IFruit {
> void eat() {
> writefln("Eat APPLE");
> }
> };
>
> PEAR = new class() IFruit {
> void eat() {
> writefln("Eat PEAR");
> }
> };
>
> PLUM = new class() IFruit {
> void eat() {
> writefln("Eat PLUM");
> }
> };
> }
>
>
> int main(string[] args) {
>
> IFruit[] fruits = [APPLE, PEAR, APPLE, APPLE, PEAR, PLUM];
>
> writefln("Fruits");
> foreach( f; fruits) {
> f.eat();
> }
>
> writefln("\nNew Fruits");
> fruits[2] = PLUM;
> foreach( f; fruits) {
> f.eat();
> }
>
> return 0;
> }
>
> [/CODE]
>
> Gide
Thanks Gide (and everybody else), I think I will implement it alike your
code.
Should be interesting enough so expect more questions in the future :)
More information about the Digitalmars-d-learn
mailing list