JScript .NET, Part IV: Inheritance: Defining Interfaces - Doc JavaScript | WebReference

JScript .NET, Part IV: Inheritance: Defining Interfaces - Doc JavaScript


JScript .NET, Part IV: Inheritance

Defining Interfaces

The Interface concept is one of the cornerstones of object oriented programming languages. Interfaces are very similar to classes. They are also defined by the exact same syntax. Interfaces differ from classes in that they don't include any member implementation. An interface can have properties and method interfaces only. An interface does not have any method implementation. It can include a method declaration but no function body.

By itself, interfaces are not very useful. You cannot create instances of interfaces. You can implement interfaces by useful classes from which you can create instances. Interfaces are instrumental in enforcing object oriented design methodologies. One group may specify the interface for other groups to follow. Each group may implement its own function bodies, but all groups will adhere to the same interface, defined a priori. It comes back to the first and foremost incentive for object oriented programming: encapsulation. You don't care how a capability is implemented. You, as a programmer, are exposed only to the interface. This is also a good way to watch after the system architecture. You don't let everyone on the team define his or her own interfaces. One central group will usually define them for the rest. Interfaces are a good way to define methods for the whole project.

A class can extend only one base class in JScript .NET. A class, though, may implement multiple interfaces. This is also called multiple inheritance. In JScript .NET, multiple inheritance is supported only for interfaces. Here are two interfaces:

interface FirstInter{
  function printSomething();
}
interface SecondInter{
  function printSomething();
}

The class myClass implements both of these interfaces, providing the body of the printSomething() function:

class myClass implements FirstInter, SecondInter {
  function printSomething() {
    print("This is something else");
  }
}

Let's create a new instance of myClass:

var demo : myClass = new myClass();

Let's define two variables as having the types of the interfaces above, and assign them the demo instance above:

var inter1 : FirstInter = demo;
var inter2 : SecondInter = demo;

Now all three variables (demo, inter1, inter2) share the same implementation of printSomething(), because they all reference the same instance, demo. The following code:

demo.printSomething();
inter1.printSomething();
inter2.printSomething();

yields three identical lines:

This is something else
This is something else
This is something else

Next: How to define abstract classes


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: May 20, 2002
Revised: May 20, 2002

URL: http://www.webreference.com/js/column110/3.html