MKoD - D Programming Language

Class Polymorphism example in D - code-name class_poly.d

Basic Newbie Stuff Class Polymorphism Example:

// ** class_poly.d - last tested with D v1.0
/+
 ' Class Polymorphism Example 
 ' --------------------------
 ' Polymorphism refers to the ability for references and collections 
 ' to hold objects of different types, and for the methods invoked on 
 ' those references to find the right type-specific behavior, with the 
 ' correct behaviour being determined at run time (this is called late 
 ' binding or dynamic binding).
 '
 ' To compile: C:\dmd\MKoD_ex>dmd class_poly.d
 +/
private import std.stdio;

// Base Class
class Location  // Implicitly inherits from object
{ 
    private char[] sName;

    // The constructor that initializes Location
    this( in char[] sName ) 
    {
        std.stdio.writefln( "Location.this( in char[] ) constructor called. sName=\"%s\"", sName );
        this.sName = sName;
    }

    public char[] Name() 
    { 
        return sName; 
    }

    public void Display() 
    {
        std.stdio.writefln( "Location Class.Display() called. sName=\"%s\"", sName );
    }

} // end class Location

// Inherits from the Location Class
class URL : Location  
{ 
    public void Navigate() 
    {
        std.stdio.writefln( "URL Class.Navigate() called. sName=\"%s\"", sName );
    }

    //this() {}

    // The constructor for URL, which calls Location's constructor
    this( in char[] sName ) 
    { 
        // Calls Base Class this( in char[] sName )
        super( sName ); 
    }

} // end class URL : Location

// Inherits from the Location Class
class LocalFile : Location 
{
    public void Execute() 
    {
        std.stdio.writefln("Executing \"%s\"", sName);
    }

    // The constructor for LocalFile, which calls URL's constructor
    this( in char[] sName ) 
    {
        // Calls Base Class this( in char[] sName )
        super( sName ); 
    }

} // end class LocalFile : Location

void main() 
{
    URL       oURL = new URL( "http://www.digitalmars.com/d/" );
    LocalFile oLoc = new LocalFile( r"C:\Windows\NotePad.exe" );

    Show( oURL );
    Show( oLoc );

} // end void main()
  
public static void Show( in Location oLoc ) 
{
    std.stdio.writef( "Location is: " );
    oLoc.Display();

} // end void Show( in Location )
C:\dmd\MKOD_ex>dmd class_poly.d
C:\dmd\bin\..\..\dm\bin\link.exe class_poly,,,user32+kernel32/noi;

C:\dmd\MKOD_ex>class_poly
Location.this( in char[] ) constructor called. sName="http://www.digitalmars.com/d/"
Location.this( in char[] ) constructor called. sName="C:\Windows\NotePad.exe"
Location is: Location Class.Display() called. sName="http://www.digitalmars.com/d/"
Location is: Location Class.Display() called. sName="C:\Windows\NotePad.exe"

C:\dmd\MKOD_ex>
Mars: fourth Rock from the Sun.