Classes (does this make sense?)

Saaa empty at needmail.com
Mon Jun 2 20:18:07 PDT 2008


>> Thanks, I changed it to this (I think I get it now :)
>> Any comments are of course still appreciated ;)
>>
>> -----------------------
>> module main;
>>
>> import std.stdio;
>> import apple;
>>
>> abstract class IFruit
>> {
>> int number;
>> void eat();
>> }
>>
>> int main(string[] args) {
>> IFruit[] fruits = [new Apple(12), new Apple];
>> writefln("Fruits");
>> foreach( f; fruits) {
>> f.eat();
>> }
>> return 0;
>> }
>> ------------------
>> module apple;
>>
>> import std.stdio;
>> import main;
>>
>> class Apple : IFruit {
>> void eat() {
>> writefln("Eat Apple");
>> }
>>
>> this ()
>> {
>> }
>>
>> this (uint color)
>> {
>> this.color=color;
>> }
>> }
>>
>>
>
> I would probably put IFruit in its own module.  Or if all the subclasses 
> are defined in the same module, at the top of that module.  It looks a bit 
> backward when the main module imports apple, then defines IFruit. This is 
> because Apple depends on IFruit, but not the other way around. Apple 
> should import IFruit, then main should import Apple.  Or main could define 
> Apple, after importing IFruit.
O.k.
>
> And IFruit probably shouldn't contain int number.  Make it a property 
> instead, this also allows IFruit to be an interface instead of an abstract 
> class:
>
> int number();   // get number
> void number(int n); // set number
>
> Drop the last one if you only want number to be readable, not writable. 
> Using properties instead of field allows the subclasses to calculate the 
> number instead of storing it, doing something extra when you set the 
> number, etc.  If you put 'int number' in the superclass, you have fixed 
> the implementation.
Why is an interface better than a abstract class?
Where should I store the number (it should have been called color, my bad )?
Every fruit has the color variable.

>
> If 'number' is the number of a kind a of fruit, it shouldn't be in a class 
> called Apple, but a class called Apples.  And IFruits.  Or you could have 
> a FruitBasket class...
Yeah, sorry. It's the color.

Thanks ;) 




More information about the Digitalmars-d-learn mailing list