spacer
Yehuda Shiran June 24, 2002
Polymorphic ToString()
Tips: June 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Google Going Native With Chrome
Mozilla Fixes Firefox Flaws as 3.5 Release Nears
Microsoft and Novell Still Bosom Buddies

The method ToString() is a good example for polymorphism. This method is defined for the Object class that is the base class for every class in the .NET framework. You can use this method for objects that are of type Object, int, or double. You can also redefine this method for a new type of object you create with a new class, without changing the way you call the method.

The following example includes the main program section and a definition of class Base. We define four variables in the main section: o, i, d, and b. The variable o is of type Object, i is of type int, d is of type double, and the variable b is of type Base. The class Base has one property (i), and it redefines the method ToString(). Instead of just converting the value of the variable to a string, the Base ToString() prints a message:

    print("i is " +  i);
and returns "foo". The main program calls ToString() with each one of the four variables: o, i, d, and b. Here is the code:

  // compile with: jsc tostring.js
 
  var o : Object = new Object();
  var i : int    = 9;
  var d : double = 5.8;
  var b : Base = new Base();
  print("i: " + i.ToString());
  print("o: " + o.ToString());
  print("d: " + d.ToString());
  print("b: " + b.ToString());
 
  class Base {
    protected var i : int = 5;
    public function ToString() : String {
      print("i is " +  i);
	  return("foo");
   }
  }
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 >
XML and PHP Simplified · Creating a ASP.NET Contact Form · Data Filtering with PHP
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Intel to Host Live Nehalem Q&A · 12 Tips to Troubleshoot Network File-Sharing · 10 Tips for Selling on Kijiji