June 24, 2002 - Polymorphic ToString()
June 24, 2002 Polymorphic ToString() Tips: June 2002
Yehuda Shiran, Ph.D.
|
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.