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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business