Classes (does this make sense?)

torhu no at spam.invalid
Mon Jun 2 19:21:35 PDT 2008


Saaa wrote:
> 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.

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.

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...


More information about the Digitalmars-d-learn mailing list