Confused about interfaces in D

Ary Borenszweig ary at esperanto.org.ar
Thu Oct 2 08:55:20 PDT 2008


ylixir wrote:
> Thomas Leonard wrote:
>> Hi,
>>
>> I'm used to interfaces in Java, and I'm wondering why this doesn't 
>> work in D:
>>
>>   interface Clock {}
>>
>>   class SystemClock : Clock {}
>>
>>   void main(string[] args) {
>>     Clock c = new SystemClock();
>>     c.toString();
>>   }
>>
>> It says:
>>
>>   $ dmd clock.d
>>   clock.d(7): Error: no property 'toString' for type 'clock.Clock'
>>
>> This compiles, though:
>>
>>     Clock c = new SystemClock();
>>     (cast(Object) c).toString();
>>
>> When is a "Clock" not an "Object"?
>>
>> Thanks,
> 
> "Clock" is never an "Object".  Object is a class every other class is 
> implicitly inherited from, and interfaces cannot be derived from 
> classes, otherwise you would wind up with the nastiness that makes 
> multiple inheritance in c++ such a nightmare (diamond shaped inheritance 
> trees, etc), and would in fact eliminate the need for interfaces 
> altogether.
> 
> casting c to Object works because SystemClock inherits from Object, 
> without the cast it doesn't work because Clock is not inherited from 
> Object.
> 
> Maybe i'm missing something, as others seem to be going on about COM 
> programming, but i don't think this has anything to do with COM, it's 
> simply that D doesn't support multiple inheritance, with good reason.

In Java you can implicitly cast an interface to an Object. This is also 
true in C#. Why? Because an interface is nothing by itself. An interface 
can only exist in runtime in the form of a class that implements it. Now 
you know that every class has Object as a top superclass. Since you can 
cast any class to Object, and since an interface can only exist in 
runtime in the form of a class, you can impllicity convert any interface 
to an Object.

This doesn't work in D because there's an interface named IUnknown used 
to do COM stuff, and classes that implement that interface don't have 
Object as the top superclass. Tihs breaks my previous "demonostration" 
(every class has Object as a top superclass).


More information about the Digitalmars-d-learn mailing list