spacer
Yehuda Shiran July 1, 2002
Calling a Polymorphic Utility
Tips: July 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

Let's look at a complete example that uses polymorphism. The main program section below creates four variables. The variable h1 is created by the CopyInt() constructor. The variable h2 is created by copying h1 with the polymorphic utility CopyMe(). The variable h3 is created by the CopyDouble() constructor, and is copied to h4 with the polymorphic utility CopyMe(). The utility CopyMe() is polymorphic because it operates on both integer and double values. The programmer who calls CopyMe() does not care how it is implemented. It is hidden from him. He or she can call CopyMe() with any object type. We print all variables at the end. Here is the code listing:

  // compile with: jsc interfacepoly.js

  interface ICopyObj {
    function Copy() : Object;
  }

  function CopyMe(ic : Object) : Object {
    return ic.Copy();
  }

  class CopyInt implements ICopyObj {
    public var i : int;
    public function CopyInt(i : int) {
      this.i = i;
    }
    public function Copy() : Object {
    return new CopyInt(i)
    }
  }

  class CopyDouble implements ICopyObj {
    public var d : double;
    public function CopyDouble(d : double) {
      this.d = d;
    }
    public function Copy() : Object {
      return new CopyDouble(d)
    }
  }

  var h1 : CopyInt = new CopyInt(8);
  var h2 : CopyInt = CopyMe(h1);
  var h3 : CopyDouble = new CopyDouble(3.2);
  var h4 : CopyDouble = CopyMe(h3);
  print("Original: " + h1.i + " Copy: " + h2.i);
  print("Original: " + h3.d + " Copy: " + h3.d);
And here is the Command Prompt window, showing the code again (interfacepoly.js), the jsc compiler's log messages, and the output of interfacepoly.exe:

To learn more about JScript .NET, go to Column 111, JScript .NET, Part V: Polymorphism.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint