CSC/ECE 517 Fall 2011/ch1 1g vn: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(128 intermediate revisions by 2 users not shown)
Line 4: Line 4:
==Overview ==
==Overview ==


'''Object Oriented Programming''' is a programming paradigm that uses abstraction to create models based on the real world. It uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Today, many popular programming languages (such as Java, JavaScript, C#, C++, Python, PHP, Ruby and Objective-C) support object-oriented programming (OOP).
In recent years, object-oriented programming has become especially popular in dynamic programming languages. Python, Ruby and Groovy are dynamic languages built on OOP principles, while Perl and PHP have been adding object-oriented features since Perl 5 and PHP 4, and ColdFusion since version 6. Over time, the scripting landscape has changed dramatically. Perl has added support for object orientation, Python has extended its object-oriented support, and more recently Ruby has made a name for itself as a full-fledged dynamic object-oriented scripting language with significant productivity benefits when compared to Java and C++. Groovy follows the lead of Ruby by offering these dynamic object orientation features. Not only does it enhance
Java by making it scriptable, but it also provides new OO features [http://en.wikipedia.org/wiki/Object-oriented_programming]


A '''Scripting language''', script language or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the end-user. Scripts are often interpreted from source code or bytecode, whereas the application is typically first compiled to native machine code.Scripting languages uses a lot of the features of object oriented languages [http://en.wikipedia.org/wiki/Scripting_language]
That scripting has developed in the shadow of object-oriented programming explains part of the problem. The two are not incompatible, but one philosophy has received the most attention. Scripting has been appearing language by language [http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4563874]


Scripting languages have their roots in the "Job Control" languages (e.g., IBM's OS JCL) that are used on "batch processing" computer systems. JCL commands tell the system to run specified programs, using particular I/O resources (e.g., files and tape drives). The "command languages" found on "time-sharing" systems (e.g., Unix and VMS) add interactive window-dressing, but perform precisely the same functions.
===Object-Oriented Languages===


In recent years, object-oriented programming has become especially popular in dynamic programming languages. Python, Ruby and Groovy are dynamic languages built on OOP principles, while Perl and PHP have been adding object oriented features since Perl 5 and PHP 4, and ColdFusion since version 6. Over time, the scripting landscape has changed dramatically. Perl has added support for object orientation, Python has extended its object-oriented support, and more recently Ruby has made a name for itself as a full-fledged dynamic object-oriented scripting language with significant productivity benefits when compared to Java and C++. Groovy follows the lead of Ruby by offering these dynamic object orientation features. Not only does it enhance
Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP, at least as an option.
Java by making it scriptable, but it also provides new OO features.


==Advantages that object orientation bring to a scripting language==
[http://en.wikipedia.org/wiki/List_of_object-oriented_programming_languages List of object-oriented programming languages ]
As object-oriented concepts continue to evolve software development, many of the software needs that are driving the object-oriented movement are the same for scripting languages. Therefore, many of the fundamental concepts of Object-oriented languages are advantages for scripting languages. In some languages, object oriented concepts are present even if one does not directly use them. For example, all variables created in Ruby or Python are references to an object, regardless of whether or not they are treated as one.
 
===Scripting Languages===
 
A scripting language, script language or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the end-user. Scripts are often interpreted from source code or bytecode, whereas the application is typically first compiled to native machine code. Early script languages were often called batch languages or job control languages. Such early scripting languages were created to shorten the traditional edit-compile-link-run process [http://en.wikipedia.org/wiki/Scripting_language]
 
==Advantages that object-orientation bring to a scripting language==
As object-oriented concepts continue to evolve software development, many of the software needs that are driving the object-oriented movement are the same for scripting languages. Therefore, many of the fundamental concepts of object-oriented languages are advantages for scripting languages. In some languages, object-oriented concepts are present even if one does not directly use them. For example, all variables created in Ruby or Python are references to an object, regardless of whether or not they are treated as one. [http://books.google.com/books/about/Scripting_with_objects.html?id=3lK3OAAACAAJ]


A few of the main concepts advantages to scripting are:
A few of the main concepts advantages to scripting are:
===Objects===


[[File:Concepts-object.gif| right| A software object.]]
[[File:Concepts-object.gif| right| A software object.]]
===Objects===


Objects are one of the key concepts in object-oriented design. When trying to understand software objects it is important to realize that they are very similar to real-world objects such as cats, desks, and cars. Real-world objects can be broken down into two fundamental characteristics: state and behavior. For example, a car object has state (color, make, model, year) and behavior (accelerate, brake, change gear).  
Objects are one of the key concepts in object-oriented design. When trying to understand software objects it is important to realize that they are very similar to real-world objects such as cats, desks, and cars. Real-world objects can be broken down into two fundamental characteristics: state and behavior. For example, a car object has state (color, make, model, year) and behavior (accelerate, brake, change gear).  


Software objects, which conceptually are similar to real-world objects, also consist of state and behavior. An objects stores its state in variables and expose its behavior through methods. When combined with scripting languages, they provide the distinct advantage of allowing a programmer to more effectively model real-world objects.
Software objects, which conceptually are similar to real-world objects, also consist of state and behavior. An objects stores its state in variables and expose its behavior through methods. When combined with scripting languages, they provide the distinct advantage of allowing a programmer to more effectively model real-world objects. [http://download.oracle.com/javase/tutorial/java/concepts/object.html]


===Encapsulation===
<br/><br/>
In Object Oriented Programming, encapsulation is an attribute of object design. It means that all of the object's data is contained and hidden in the object and access to it restricted to members of that class.
<b>Image on right is a visual representation of a software object.</b>
<br/><br/><br/><br/>
 
===Classes===


The most common levels of access are:
A class in object-oriented programming is a construct which is used as a blueprint to create instances of itself. The class objects are also called as instance objects or just objects. A class can have data members or functions which enable its objects to define functionality, behavior and maintain its state. It represents a noun, such as a person, place or (possibly quite abstract) thing, or something nominalized. For example, "Banana" is an instance of the class "Fruit" (a "Fruit" object). It is of the type "Fruit". Programming languages that include classes as a programming construct offer support for various class-related features [http://en.wikipedia.org/wiki/Class_%28computer_programming%29]
*Public : All objects can access it.
*Protected : Access is limited to members of the same class or subclass.
*Private : Access is limited to members of the same class.


===Inheritance===
===Inheritance===
Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Another important concept of object-oriented programming is inheritance. Inheritance allows a class to copy all the state and behavior of another class and then modify and extend these attributes to provide a more custom approach for the problem at hand. Any class that extends from another class is called a subclass. The class a subclass inherits from is called the superclass. The two major types of inheritance are single and multiple inheritance.


Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:
<b>Single Inheritance</b><br/>
Single inheritance is when a subclass only inherits from a single base class.


===Interfaces===
Example [http://www.inf.ufsc.br/poo/smalltalk/ibm/tutorial/oop.html]:
As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.
<pre>
class Student {
String name;
String address;
int age;
float gpa;
}
 
class Undergraduate extends Student {
String year; // Freshman, Sophomore, Junior, or Senior
}
 
class Graduate extends Student {
String program;  // Either graduate or PhD
}
</pre>


In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
Both a Graduate class and Undergraduate class have similar behavior such as managing a name, an address, a major, and a GPA. Rather than put this behavior in both of these classes, the behavior is placed in a new class called Student. Both Graduate and Undergraduate become subclass of the Student class, and both inherit the Student behavior.
Both Graduate and Undergraduate classes can then add additional behavior that is unique to them. For example, Graduate can be either Master's program or PhD program. On the other hand, the
Undergraduate class might want to keep track of either the student is Freshman, Sophomore, Junior or Senior.


<b>Multiple Inheritance</b><br/>
Multiple inheritance is when a subclass inherits from multiple base classes.
Example [http://www.java-samples.com/showtutorial.php?tutorialid=462]:
<pre>
<pre>
interface Bicycle {
class Horse {
public:
Horse() { cout << "Horse constructor... "; }
virtual ~Horse() { cout << "Horse destructor... "; }
virtual void Whinny() const { cout << "Whinny!... "; }
private:
int itsAge;
};
 
class Bird {
public:
Bird() { cout << "Bird constructor... "; }
virtual ~Bird() { cout << "Bird destructor... "; }
virtual void Chirp() const { cout << "Chirp... ";  }
virtual void Fly() const {
cout << "I can fly! I can fly! I can fly! ";
}
private:
int itsWeight;
};
 
class Pegasus : public Horse, public Bird {
public:
void Chirp() const { Whinny(); }
Pegasus() { cout << "Pegasus constructor... "; }
~Pegasus() { cout << "Pegasus destructor...  "; }
};
</pre>
 
Pegasus, which is a horse that can fly, inherits from both the Horse and the Bird classes. However, since Pegasus cannot chirp, the inherited Chirp function from the Bird class is overwritten with the Whinny function.
 
===Polymorphism===
Polymorphism, from the perspective of object-oriented languages, is the ability for functions and objects to have many forms. It is a very powerful tool that allows programmers to separate the interface from the implementation.
 
Consider the following example [http://www3.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInheritancePolymorphism.html]:
 
[[File:OOP_PolymorphismShape.png| left| Polymorphism Example.]]


      void changeCadence(int newValue);  // wheel revolutions per minute
<br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>


      void changeGear(int newValue);
Suppose that our application uses many types of shapes, such as rectangles, and triangles. We can create a base Shape class that defines the public interface for all of the different types of shapes. In this case, we want all shapes to have a getArea() method.


      void speedUp(int increment);
Here is one possible implementation of the Shape class:


      void applyBrakes(int decrement);
<pre>
public class Shape {
  private String color;
 
  public Shape (String color) {
      this.color = color;
  }
 
  // All shapes must has a method called getArea()
  public double getArea() {
      System.err.println("Shape unknown! Cannot compute area!");
      return 0;  // Need a return to compile the program
  }
 
  public String toString() {
      return "Shape of color=\"" + color + "\"";
  }
}
}
</pre>
</pre>


To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
Since the Shape class does not know what type of shape it is dealing with, it just prints out an error message when its getArea() method is called.


Now deriving the Rectangle and Triangle subclasses:
<pre>
<pre>
class ACMEBicycle implements Bicycle {
public class Rectangle extends Shape {
 
  private int length;
   // remainder of this class implemented as before
  private int width;
 
 
  public Rectangle(String color, int length, int width) {
      super(color);
      this.length = length;
      this.width = width;
  }
 
  @Override
  public String toString() {
      return "Rectangle of length=" + length + " and width=" + width + ", subclass of " + super.toString();
  }
 
  @Override
  public double getArea() {
      return length*width;
   }
}
</pre>
<pre>
public class Triangle extends Shape {
  private int base;
  private int height;
 
  public Triangle(String color, int base, int height) {
      super(color);
      this.base = base;
      this.height = height;
  }
 
  @Override
  public String toString() {
      return "Triangle of base=" + base + " and height=" + height + ", subclass of " + super.toString();
  }
 
  @Override
  public double getArea() {
      return 0.5*base*height;
  }
}
}
</pre>
</pre>


Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Therefore, due to polymorphism, all the shape subclasses will compute their area based on their corresponding area formula. All Rectangle objects will compute their area as length * width, while all Triangle objects will use 0.5 * base * height.


Interfaces can be very useful in scripting where implementations of an class may need to change frequently.  
===Encapsulation===
Encapsulation, which is most often achieved through information hiding, allows a programmer to hide the implementation details of an object. Only state and behavior of an object that are designated as public can be viewed from outside its scope. This provides an important advantage to scripting languages by preventing objects from accidentally modifying attributes in another object that may be vital to the scripts functionality.
 
In most programming languages, the common levels of access to an object are:
*Public : All objects can access it.
*Protected : Access is limited to members of the same class or subclass.
*Private : Access is limited to members of the same class. [http://books.google.com/books/about/Object_oriented_analysis_and_design_with.html?id=3NQgAQAAIAAJ]


===Code Reuse===
===Code Reuse===
Object oriented design promotes code reuse by allowing programmers to take preexisting classes and integrating them into new scripts. This helps to improve readability of the code as well as promoting the "Don't Repeat Yourself" principle, which aims at reducing repetition of information.
Object-oriented design promotes code reuse by allowing programmers to take preexisting classes and integrating them into new scripts. This helps to improve readability of the code as well as promoting the "Don't Repeat Yourself" principle, which aims at reducing repetition of information. [http://www.artima.com/intv/dry.html]


==Advantages that scripting capability bring to an object-oriented language==
==Advantages that scripting capability bring to an object-oriented language==
Scripting provides a few advantages to object-oriented languages:
Scripting provides a few advantages to object-oriented languages:
===Interpreted Code===
One of the main differences between scripting languages and system programming languages is that the scripting languages are interpreted whereas system programming languages are mostly compiled. Being an interpreted language, scripting languages make applications flexible, provide rapid turnaround while in development, eliminates compile time errors, and  allows for code generation on the fly [http://www.tcl.tk/doc/scripting.html].


===Dynamic Typing===
===Dynamic Typing===
Scripting languages were originally designed to serve as tools for automating repetitive tasks such as rotating a system log. In order to permit easy interfacing between components, a script language must be as typeless as possible. In strongly typed languages, extra code may be required in order to allow to components to communicate. This dynamic typing provides a distinct advantage that eventually made its way into popular programming languages such as Python and Ruby.
Scripting languages were originally designed to serve as tools for automating repetitive tasks such as rotating a system log. In order to permit easy interfacing between components, a script language must be as typeless as possible. In strongly typed languages, extra code may be required in order to allow to components to communicate. This dynamic typing provides a distinct advantage that eventually made its way into popular programming languages such as Python and Ruby [http://books.google.com/books/about/Scripting_with_objects.html?id=3lK3OAAACAAJ].


===Glue code===
===Glue Code===
While not contributing any functionality to a program, glue code allows a programmer to bring together two different pieces of code that normally would be incompatible together.
While not contributing any additional functionality to a program, glue code allows a programmer to connect two different pieces of existing code that were not designed to work together.  
[http://www.site.uottawa.ca:4321/oose/index.html#gluecode]


==Are there any advantages to a scripting language that is not object oriented?==
==Are there any advantages to a scripting language that is not object-oriented?==


The only advantage to a scripting language that is not object oriented is that it makes it a little easier if the language used for a particular project doesn’t require much complexity and OOP features don’t really make a difference. There are many non-object-oriented scripting languages in use, or scripting languages that have "object extensions" that often go unused like Perl, PHP, and various UNIX shells.  
The only advantage to a scripting language that is not object-oriented is that it makes it a little easier if the language used for a particular project doesn’t require much complexity and OOP features don’t really make a difference. There are many non-object-oriented scripting languages in use, or scripting languages that have "object extensions" that often go unused like Perl, PHP, and various UNIX shells.  


All these languages enable one to write small programs very quickly and efficiently without any complexity of OOP features. Scripting languages that have OO tacked onto them like PERL, for instance, added the "my" keyword.  
All these languages enable one to write small programs very quickly and efficiently without any complexity of OOP features. Perl was not originally designed or implemented as an object-oriented language. Its version of object-orientation is simple and well integrated, but not fundamental to the language. In a larger system, an object-oriented implementation of a system in Perl will almost never be faster than the equivalent non-object-oriented implementation [http://www.manning.com/conway/excerpt_preface.html]


Tcl also did not originally support object oriented (OO) syntax before 8.6, so OO functionality was provided by extension packages, such as [http://en.wikipedia.org/wiki/Incr_Tcl incr Tcl] and [http://en.wikipedia.org/wiki/XOTcl XOTcl].
Tcl also did not originally support object-oriented (OO) syntax before 8.6, so OO functionality was provided by extension packages, such as [http://en.wikipedia.org/wiki/Incr_Tcl incr Tcl] and [http://en.wikipedia.org/wiki/XOTcl XOTcl]. Tcl is more suited at OO in the large than OO in the small. Fine-grained "an int is an object" OO would not fit well in Tcl. Everything is a string, after all [http://equi4.com/moam/strength.html]
 
[http://www.toves.org/books/php/ch03-first/index.html A non-object-oriented PHP program ]
<pre>
<html>
<head><title>Random</title></head>
<body>
<p>I have randomly selected the number
<?php $choice=rand(1,100); echo $choice;?>.
Its square root is <?php echo sqrt($choice);?>.</p>
</body>
</html>
</pre>


==Is scripting essentially synonymous with dynamic typing?==
==Is scripting essentially synonymous with dynamic typing?==


[[File:DegreeofTyping.jpg |right]]
[[File:DegreeofTyping.jpg |right]]
The figure on the right shows a comparison of various programming languages based on their level (higher level language execute more machine instructions for each language statement) and their degree of typing. System programming languages like C tend to be strongly typed and medium level (5-10 instructions/statement). Scripting language like Tcl tend to be weakly typed and vey high level (100-1000 instructions/statement) [http://www.tcl.tk/doc/scripting.html#921216]
Scripting languages are dynamically typed, usually interpreted, and very high-level for e.g. Perl, Tcl, Python, Rexx, Visual Basic). Because of dynamic typing and interpretation they are very flexible and encourage experimentation [http://books.google.com/books/about/The_world_of_scripting_languages.html?id=ZpFQAAAAMAAJ]


Dynamic typing is not so important for Scripting languages but usually they are interpreted and dynamically typed. For e.g. scripting languages (e.g. Perl, Tcl, Python, Rexx, Visual Basic) are dynamically typed, usually interpreted, and very high-level. Because of dynamic typing and interpretation they are very flexible and encourage experimentation.  
The figure on the right shows a comparison of various programming languages based on their level (higher level language execute more machine instructions for each language statement) and their degree of typing. System programming languages like C tend to be strongly typed and medium level (5-10 instructions/statement). Scripting language like Tcl tend to be weakly typed and very high level (100-1000 instructions/statement) [http://www.tcl.tk/doc/scripting.html#921216]
   
   
Objects in scripting languages tend to be typeless. To enable easy interfacing between the components that are combined together in a script.  In a typeless environment, the output of one can be taken as a generic system of bytes and accepted by the receiving component just on that basis. Or, as is more commonly the case with scripting languages because string processing is main focus of such languages, the components can be assumed to produce characters at their outputs and to accept character streams at their inputs.  
Objects in scripting languages tend to be typeless. To enable easy interfacing between the components that are combined together in a script.  In a typeless environment, the output of one can be taken as a generic system of bytes and accepted by the receiving component just on that basis. Or, as is more commonly the case with scripting languages because string processing is main focus of such languages, the components can be assumed to produce characters at their outputs and to accept character streams at their inputs.  


Python is dynamically typed, so there is no need for variable declarations. This reduces the amount of code that students have to write and also eliminates common errors stemming from misunderstanding the subtle distinctions of declaration, definition and use [http://www.jython.org/docs/tutorial/indexprogress.html]
Perl is known as one of "the three Ps" (along with Python and PHP), the most popular dynamic languages for writing Web applications. Python is dynamically typed, so there is no need for variable declarations. This reduces the amount of code that students have to write and also eliminates common errors stemming from misunderstanding the subtle distinctions of declaration, definition and use  
[http://www.jython.org/docs/tutorial/indexprogress.html] Ruby also features dynamic typing.
<br>
[http://www.dreamincode.net/forums/topic/179748-dynamic-typing/ The following program shows power and simplicity of dynamic typing in Ruby]
<pre>
class Class
    def attr_reader2(*vars)
        vars.each do |symbol|
            define_method(symbol) { instance_variable_get "@#{symbol}" }
        end
    end
    def attr_writer2(*vars)
        vars.each do |symbol|
            define_method("#{symbol}=") { |value| instance_variable_set("@#{symbol}", value) }
        end
    end
    def attr_accessor2(*vars)
        attr_reader2(*vars)
        attr_writer2(*vars)
    end
end
</pre>


==Object Oriented Scripting Languages==
==Object-Oriented Scripting Languages==
=== AppleScript===
=== AppleScript===
[http://developer.apple.com/library/mac/#documentation/AppleScript/Conceptual/AppleScriptX/Concepts/ScriptingOnOSX.html%23//apple_ref/doc/uid/20000032-BABEBGCF AppleScript] is a scripting language created by Apple Inc., through which scriptable applications and parts of Mac OS can be controlled directly. AppleScript scripting language appears to be a simple language but it is a very rich, object-oriented language, capable of performing complex programming tasks. It has the concept of classes and objects. It is basically an inter-application processing system, intended to exchange data between different applications and control them to automate recurring tasks.  
[http://developer.apple.com/library/mac/#documentation/AppleScript/Conceptual/AppleScriptX/Concepts/ScriptingOnOSX.html%23//apple_ref/doc/uid/20000032-BABEBGCF AppleScript] is a scripting language created by Apple Inc., through which scriptable applications and parts of Mac OS can be controlled directly. AppleScript scripting language appears to be a simple language but it is a very rich, object-oriented language, capable of performing complex programming tasks. It has the concept of classes and objects. It is basically an inter-application processing system, intended to exchange data between different applications and control them to automate recurring tasks.  
Line 123: Line 286:
A modern web document, which comprises of different building blocks mostly requires various kinds of methods of implementation: different languages, different tools, different frameworks and sometimes completely different teams. The biggest problem has been getting all of these blocks to communicate with each other in a consistent manner. Curl attempts to side step these problems by providing a consistent syntactic and semantic interface at all levels of web content creation: from simple HTML to complex object-oriented programming.
A modern web document, which comprises of different building blocks mostly requires various kinds of methods of implementation: different languages, different tools, different frameworks and sometimes completely different teams. The biggest problem has been getting all of these blocks to communicate with each other in a consistent manner. Curl attempts to side step these problems by providing a consistent syntactic and semantic interface at all levels of web content creation: from simple HTML to complex object-oriented programming.
Curl combines text markup (as in HTML), scripting (as in JavaScript), and heavy-duty computing (as in Java, C#, or C++) within one common framework. It is used in a range of internal enterprise, B2B, and B2C applications.
Curl combines text markup (as in HTML), scripting (as in JavaScript), and heavy-duty computing (as in Java, C#, or C++) within one common framework. It is used in a range of internal enterprise, B2B, and B2C applications.
<br>
[http://curl.com/products/prod/language/#op Java-Like Object Oriented Programming]
<pre>
<pre>
{Curl 5.0, 6.0, 7.0 applet}
{curl 6.0 applet}
{text
{curl-file-attributes character-encoding = "shift-j is"}
   color = "blue",
{define-class public Foo
   font-size = 16pt,
{method public {hello}:void
   Hello World}
   {popup-message "Hello!"}
}
{define-class public Bar {inherits Foo}
  {method public {hello}:void
    {popup-message "Hello World!"}
}
{ do
   let foo:Foo = {Bar}
   {foo.hello}
}
</pre>
</pre>


Line 164: Line 338:
obj.SetX(14);
obj.SetX(14);
document.write(' ' + obj.GetX() + ' ' + obj2.GetX());
document.write(' ' + obj.GetX() + ' ' + obj2.GetX());
</pre>
===Lua===
[http://www.lua.org/ Lua] is a powerful, fast, lightweight, embeddable scripting language. Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping.
<br>
[http://lua-users.org/wiki/MetamethodsTutorial String Class Example]
<pre>
> mt = {}  -- metatable
>
> function String(s)
>>  return setmetatable({ value = s or '' }, mt)
>> end
>
> function mt.__add(a, b)
>>  return String(a.value .. b.value)
>> end
>
> function mt.__mul(a, b)
>>  return String(string.rep(a.value, b))
>> end
>
> s = String('hello ')
>
> print(s.value)
hello
> print( (s + String('Lua user')).value )  -- concat 2 String instances
hello Lua user
> print( (s*3).value )
hello hello hello
> print( (((s + String('Lua user.')))*2).value )  -- use both metamethods
hello Lua user.hello Lua user.
</pre>
</pre>


Line 267: Line 410:
[http://en.wikipedia.org/wiki/Python_(programming_language) Python] is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java. Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. The class statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming. Python allows programmers to define their own types using classes, which are most often used for object-oriented programming.
[http://en.wikipedia.org/wiki/Python_(programming_language) Python] is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java. Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. The class statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming. Python allows programmers to define their own types using classes, which are most often used for object-oriented programming.
<br>
<br>
[http://en.wikibooks.org/wiki/Python_Programming/Object-oriented_programming Constructing a class]
[http://docs.python.org/tutorial/classes.html An object oriented program in Python]
<pre>
<pre>
class Car:
# Function defined outside the class
    def brake(self):
def f1(self, x, y):
        print("Brakes")
    return min(x, x+y)
 
     def accelerate(self):
class C:
         print("Accelerating")
    f = f1
     def g(self):
         return 'hello world'
    h = g
</pre>
</pre>


Line 339: Line 485:
</pre>
</pre>


==Conclusion==
==References==


==References==
1. Object-oriented programming http://en.wikipedia.org/wiki/Object-oriented_programming
[1]https://developer.mozilla.org/En/Introduction_to_Object-Oriented_JavaScript
<br>
2. Loui, R. (2008). In Praise of Scripting: Real Programming Pragmatism , IEEE Computer, vol. 41, no. 7.
<br>
3. Scripting Language http://en.wikipedia.org/wiki/Scripting_language
<br>
4, 13. Kak, A. C. (2008). Scripting With Objects. Hoboken, NJ: John Wiley & Sons.
<br>
5. What is an Object? http://download.oracle.com/javase/tutorial/java/concepts/object.html
<br>
6. Classes http://en.wikipedia.org/wiki/Class_%28computer_programming%29
<br>
7. Single Inheritance http://www.inf.ufsc.br/poo/smalltalk/ibm/tutorial/oop.html
<br>
8. Multiple Inheritance http://www.java-samples.com/showtutorial.php?tutorialid=462
<br>
9. Polymorphism http://www3.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInheritancePolymorphism.html
<br>
10. Booch, G., Maksimchuk, R. A., Engle, M. W., Young, B. J., Conallen, J., & Houston, K. A. (2007). Object-Oriented Analysis and Design With Applications, Third Edition. Upper Saddle River, NJ: Addison-Wesley.
<br>
11. Don't Repeat Yourself http://www.artima.com/intv/dry.html
<br>
12, 18. Scripting http://www.tcl.tk/doc/scripting.html
<br>
14. Glue Code http://www.site.uottawa.ca:4321/oose/index.html#gluecode
<br>
15. What object-oriented Perl isn't http://www.manning.com/conway/excerpt_preface.html
<br>
16. The strength on Tcl http://equi4.com/moam/strength.html
<br>
17. Barron, D., & Barron, W. D. (2000). The world of scripting languages (August 2000 ed.). NY: John Wiley & Sons
<br>
19. The Jython Tutorial http://www.jython.org/docs/tutorial/indexprogress.html
<br>
20. Object Oriented Programming in JavaScript http://mckoss.com/jscript/object.htm
<br>
21. Open Object Rexx http://www.oorexx.org/docs/rexxref/c188.htm
<br>
22. Tcl Core http://www.tcl.tk/man/tcl8.6/TclCmd/class.htm#M13

Latest revision as of 03:15, 26 September 2011

Object-Oriented Languages and Scripting

Overview

In recent years, object-oriented programming has become especially popular in dynamic programming languages. Python, Ruby and Groovy are dynamic languages built on OOP principles, while Perl and PHP have been adding object-oriented features since Perl 5 and PHP 4, and ColdFusion since version 6. Over time, the scripting landscape has changed dramatically. Perl has added support for object orientation, Python has extended its object-oriented support, and more recently Ruby has made a name for itself as a full-fledged dynamic object-oriented scripting language with significant productivity benefits when compared to Java and C++. Groovy follows the lead of Ruby by offering these dynamic object orientation features. Not only does it enhance Java by making it scriptable, but it also provides new OO features [1]

That scripting has developed in the shadow of object-oriented programming explains part of the problem. The two are not incompatible, but one philosophy has received the most attention. Scripting has been appearing language by language [2]

Object-Oriented Languages

Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP, at least as an option.

List of object-oriented programming languages

Scripting Languages

A scripting language, script language or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the end-user. Scripts are often interpreted from source code or bytecode, whereas the application is typically first compiled to native machine code. Early script languages were often called batch languages or job control languages. Such early scripting languages were created to shorten the traditional edit-compile-link-run process [3]

Advantages that object-orientation bring to a scripting language

As object-oriented concepts continue to evolve software development, many of the software needs that are driving the object-oriented movement are the same for scripting languages. Therefore, many of the fundamental concepts of object-oriented languages are advantages for scripting languages. In some languages, object-oriented concepts are present even if one does not directly use them. For example, all variables created in Ruby or Python are references to an object, regardless of whether or not they are treated as one. [4]

A few of the main concepts advantages to scripting are:

Objects

A software object.
A software object.

Objects are one of the key concepts in object-oriented design. When trying to understand software objects it is important to realize that they are very similar to real-world objects such as cats, desks, and cars. Real-world objects can be broken down into two fundamental characteristics: state and behavior. For example, a car object has state (color, make, model, year) and behavior (accelerate, brake, change gear).

Software objects, which conceptually are similar to real-world objects, also consist of state and behavior. An objects stores its state in variables and expose its behavior through methods. When combined with scripting languages, they provide the distinct advantage of allowing a programmer to more effectively model real-world objects. [5]



Image on right is a visual representation of a software object.



Classes

A class in object-oriented programming is a construct which is used as a blueprint to create instances of itself. The class objects are also called as instance objects or just objects. A class can have data members or functions which enable its objects to define functionality, behavior and maintain its state. It represents a noun, such as a person, place or (possibly quite abstract) thing, or something nominalized. For example, "Banana" is an instance of the class "Fruit" (a "Fruit" object). It is of the type "Fruit". Programming languages that include classes as a programming construct offer support for various class-related features [6]

Inheritance

Another important concept of object-oriented programming is inheritance. Inheritance allows a class to copy all the state and behavior of another class and then modify and extend these attributes to provide a more custom approach for the problem at hand. Any class that extends from another class is called a subclass. The class a subclass inherits from is called the superclass. The two major types of inheritance are single and multiple inheritance.

Single Inheritance
Single inheritance is when a subclass only inherits from a single base class.

Example [7]:

class Student {
	String name; 
	String address;
	int age;
	float gpa;
}

class Undergraduate extends Student {
	String year; // Freshman, Sophomore, Junior, or Senior
}

class Graduate extends Student {
	String program;  // Either graduate or PhD
}

Both a Graduate class and Undergraduate class have similar behavior such as managing a name, an address, a major, and a GPA. Rather than put this behavior in both of these classes, the behavior is placed in a new class called Student. Both Graduate and Undergraduate become subclass of the Student class, and both inherit the Student behavior. Both Graduate and Undergraduate classes can then add additional behavior that is unique to them. For example, Graduate can be either Master's program or PhD program. On the other hand, the Undergraduate class might want to keep track of either the student is Freshman, Sophomore, Junior or Senior.

Multiple Inheritance
Multiple inheritance is when a subclass inherits from multiple base classes.

Example [8]:

class Horse {
	public:
		Horse() { cout << "Horse constructor... "; }
		virtual ~Horse() { cout << "Horse destructor... "; }
		virtual void Whinny() const { cout << "Whinny!... "; }
	private:
		int itsAge;
};

class Bird {
	public:
		Bird() { cout << "Bird constructor... "; }
		virtual ~Bird() { cout << "Bird destructor... "; }
		virtual void Chirp() const { cout << "Chirp... ";  }
		virtual void Fly() const { 
			cout << "I can fly! I can fly! I can fly! "; 
		}
		private:
		int itsWeight;
};

class Pegasus : public Horse, public Bird {
	public:
		void Chirp() const { Whinny(); }
		Pegasus() { cout << "Pegasus constructor... "; }
		~Pegasus() { cout << "Pegasus destructor...  "; }
};

Pegasus, which is a horse that can fly, inherits from both the Horse and the Bird classes. However, since Pegasus cannot chirp, the inherited Chirp function from the Bird class is overwritten with the Whinny function.

Polymorphism

Polymorphism, from the perspective of object-oriented languages, is the ability for functions and objects to have many forms. It is a very powerful tool that allows programmers to separate the interface from the implementation.

Consider the following example [9]:

Polymorphism Example.
Polymorphism Example.


















Suppose that our application uses many types of shapes, such as rectangles, and triangles. We can create a base Shape class that defines the public interface for all of the different types of shapes. In this case, we want all shapes to have a getArea() method.

Here is one possible implementation of the Shape class:

public class Shape {
   private String color;
   
   public Shape (String color) {
      this.color = color;
   }
   
   // All shapes must has a method called getArea()
   public double getArea() {
      System.err.println("Shape unknown! Cannot compute area!");
      return 0;   // Need a return to compile the program
   }
   
   public String toString() {
      return "Shape of color=\"" + color + "\"";
   }
}

Since the Shape class does not know what type of shape it is dealing with, it just prints out an error message when its getArea() method is called.

Now deriving the Rectangle and Triangle subclasses:

public class Rectangle extends Shape {
   private int length;
   private int width;
   
   public Rectangle(String color, int length, int width) {
      super(color);
      this.length = length;
      this.width = width;
   }
   
   @Override
   public String toString() {
      return "Rectangle of length=" + length + " and width=" + width + ", subclass of " + super.toString();
   }
   
   @Override
   public double getArea() {
      return length*width;
   }
}
public class Triangle extends Shape {
   private int base;
   private int height;
   
   public Triangle(String color, int base, int height) {
      super(color);
      this.base = base;
      this.height = height;
   }
   
   @Override
   public String toString() {
      return "Triangle of base=" + base + " and height=" + height + ", subclass of " + super.toString();
   }
   
   @Override
   public double getArea() {
      return 0.5*base*height;
   }
}

Therefore, due to polymorphism, all the shape subclasses will compute their area based on their corresponding area formula. All Rectangle objects will compute their area as length * width, while all Triangle objects will use 0.5 * base * height.

Encapsulation

Encapsulation, which is most often achieved through information hiding, allows a programmer to hide the implementation details of an object. Only state and behavior of an object that are designated as public can be viewed from outside its scope. This provides an important advantage to scripting languages by preventing objects from accidentally modifying attributes in another object that may be vital to the scripts functionality.

In most programming languages, the common levels of access to an object are:

  • Public : All objects can access it.
  • Protected : Access is limited to members of the same class or subclass.
  • Private : Access is limited to members of the same class. [10]

Code Reuse

Object-oriented design promotes code reuse by allowing programmers to take preexisting classes and integrating them into new scripts. This helps to improve readability of the code as well as promoting the "Don't Repeat Yourself" principle, which aims at reducing repetition of information. [11]

Advantages that scripting capability bring to an object-oriented language

Scripting provides a few advantages to object-oriented languages:

Interpreted Code

One of the main differences between scripting languages and system programming languages is that the scripting languages are interpreted whereas system programming languages are mostly compiled. Being an interpreted language, scripting languages make applications flexible, provide rapid turnaround while in development, eliminates compile time errors, and allows for code generation on the fly [12].

Dynamic Typing

Scripting languages were originally designed to serve as tools for automating repetitive tasks such as rotating a system log. In order to permit easy interfacing between components, a script language must be as typeless as possible. In strongly typed languages, extra code may be required in order to allow to components to communicate. This dynamic typing provides a distinct advantage that eventually made its way into popular programming languages such as Python and Ruby [13].

Glue Code

While not contributing any additional functionality to a program, glue code allows a programmer to connect two different pieces of existing code that were not designed to work together. [14]

Are there any advantages to a scripting language that is not object-oriented?

The only advantage to a scripting language that is not object-oriented is that it makes it a little easier if the language used for a particular project doesn’t require much complexity and OOP features don’t really make a difference. There are many non-object-oriented scripting languages in use, or scripting languages that have "object extensions" that often go unused like Perl, PHP, and various UNIX shells.

All these languages enable one to write small programs very quickly and efficiently without any complexity of OOP features. Perl was not originally designed or implemented as an object-oriented language. Its version of object-orientation is simple and well integrated, but not fundamental to the language. In a larger system, an object-oriented implementation of a system in Perl will almost never be faster than the equivalent non-object-oriented implementation [15]

Tcl also did not originally support object-oriented (OO) syntax before 8.6, so OO functionality was provided by extension packages, such as incr Tcl and XOTcl. Tcl is more suited at OO in the large than OO in the small. Fine-grained "an int is an object" OO would not fit well in Tcl. Everything is a string, after all [16]

A non-object-oriented PHP program

<html>
<head><title>Random</title></head>
<body>
<p>I have randomly selected the number
<?php $choice=rand(1,100); echo $choice;?>.
Its square root is <?php echo sqrt($choice);?>.</p>
</body>
</html>

Is scripting essentially synonymous with dynamic typing?

Scripting languages are dynamically typed, usually interpreted, and very high-level for e.g. Perl, Tcl, Python, Rexx, Visual Basic). Because of dynamic typing and interpretation they are very flexible and encourage experimentation [17]

The figure on the right shows a comparison of various programming languages based on their level (higher level language execute more machine instructions for each language statement) and their degree of typing. System programming languages like C tend to be strongly typed and medium level (5-10 instructions/statement). Scripting language like Tcl tend to be weakly typed and very high level (100-1000 instructions/statement) [18]

Objects in scripting languages tend to be typeless. To enable easy interfacing between the components that are combined together in a script. In a typeless environment, the output of one can be taken as a generic system of bytes and accepted by the receiving component just on that basis. Or, as is more commonly the case with scripting languages because string processing is main focus of such languages, the components can be assumed to produce characters at their outputs and to accept character streams at their inputs.

Perl is known as one of "the three Ps" (along with Python and PHP), the most popular dynamic languages for writing Web applications. Python is dynamically typed, so there is no need for variable declarations. This reduces the amount of code that students have to write and also eliminates common errors stemming from misunderstanding the subtle distinctions of declaration, definition and use [19] Ruby also features dynamic typing.
The following program shows power and simplicity of dynamic typing in Ruby

class Class
    def attr_reader2(*vars)
        vars.each do |symbol|
            define_method(symbol) { instance_variable_get "@#{symbol}" }
        end
    end
    def attr_writer2(*vars)
        vars.each do |symbol|
            define_method("#{symbol}=") { |value| instance_variable_set("@#{symbol}", value) }
        end
    end
    def attr_accessor2(*vars)
        attr_reader2(*vars)
        attr_writer2(*vars)
    end
end

Object-Oriented Scripting Languages

AppleScript

AppleScript is a scripting language created by Apple Inc., through which scriptable applications and parts of Mac OS can be controlled directly. AppleScript scripting language appears to be a simple language but it is a very rich, object-oriented language, capable of performing complex programming tasks. It has the concept of classes and objects. It is basically an inter-application processing system, intended to exchange data between different applications and control them to automate recurring tasks.
Example of a simple script with one property, one handler, one nested script object, and an implicit run handler with two statements

property defaultClientName : "Mary Smith"
on greetClient(nameOfClient)
    display dialog ("Hello " & nameOfClient & "!")
end greetClient
 script testGreet
    greetClient(defaultClientName)
end script
run testGreet --result: "Hello Mary Smith!"
greetClient("Joe Jones") --result: "Hello Joe Jones!"

Curl

Curl is a reflective object-oriented programming language for interactive web applications whose goal is to provide a effortless transition between formatting and programming. Curl is a markup language like and also includes an object-oriented programming language that supports multiple inheritance.

A modern web document, which comprises of different building blocks mostly requires various kinds of methods of implementation: different languages, different tools, different frameworks and sometimes completely different teams. The biggest problem has been getting all of these blocks to communicate with each other in a consistent manner. Curl attempts to side step these problems by providing a consistent syntactic and semantic interface at all levels of web content creation: from simple HTML to complex object-oriented programming. Curl combines text markup (as in HTML), scripting (as in JavaScript), and heavy-duty computing (as in Java, C#, or C++) within one common framework. It is used in a range of internal enterprise, B2B, and B2C applications.
Java-Like Object Oriented Programming

{curl 6.0 applet}
{curl-file-attributes character-encoding = "shift-j is"}
{define-class public Foo
 {method public {hello}:void
   {popup-message "Hello!"}
}
{define-class public Bar {inherits Foo}
  {method public {hello}:void
     {popup-message "Hello World!"}
}
{ do
   let foo:Foo = {Bar}
   {foo.hello}
}

Groovy

Groovy is an object-oriented programming scripting language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL. It makes testing simpler by supporting unit testing and mocking out-of-the-box. It seamlessly integrates with all existing Java classes and libraries. Groovy uses a Java-like bracket syntax. It is dynamically compiled to Java Virtual Machine (JVM) bytecode and interoperates with other Java code and libraries.

class Greet {
  def name
  Greet(who) { name = who[0].toUpperCase() +
                      who[1..-1] }
  def salute() { println "Hello $name!" }
}

g = new Greet('world')  // create object
g.salute()              // Output "Hello World!"

JavaScript

JavaScript, also known as Mocha, LiveScript, JScript, and ECMAScript, is one of the world's most popular programming languages. It is a class-free, object-oriented language, and uses prototypal inheritance instead of classical inheritance. It is a prototype-based scripting language, which is dynamic, weakly typed, and has first-class functions. It is a multi-paradigm language, which supports object-oriented, imperative, and functional programming styles. It supports OOP because it supports inheritance through prototyping as well as properties and methods. Many developers cast off JS as a suitable OOP language because they are so used to the class style of C# and Java. The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and that interact with the Document Object Model (DOM) of the page. JavaScript is an excellent language to write object oriented web applications. It can support OOP because it supports Encapsulation, Polymorphism and inheritance through prototyping as well as properties and methods [20]

 
function A()
{
    var x = 7;
 
    this.GetX = function() { return x;}
    this.SetX = function(xT) { x = xT; }
}
 
obj = new A;
obj2 = new A;
document.write(obj.GetX() + ' ' + obj2.GetX());
obj.SetX(14);
document.write(' ' + obj.GetX() + ' ' + obj2.GetX());

Object Rexx

Object REXX programming language is an object-oriented scripting language initially produced by IBM for OS/2. As an object-oriented language, Rexx provides data encapsulation, polymorphism, an object class hierarchy, class-based inheritance of methods, and concurrency[21] It includes a number of useful base classes and allows you create new object classes of your own.
factorialProgram.rex -- computes the factorial of a number

  arg N .
  call factorial N
  say result
  exit 0 /* don't fall through to the PROCEDURE instruction */
  factorial : PROCEDURE
  n = arg( 1 )
  if n  = 1 then
    return 1 
  return n * factorial( n - 1 )

Perl 5

Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. There are three main terms, explained from the point of view of how Perl handles objects. The terms are object, class, and method.

  • Within Perl, an object is merely a reference to a data type that knows what class it belongs to. The object is stored as a reference in a scalar variable.
  • A class within Perl is a package that contains the corresponding methods required to create and manipulate objects.
  • A method within Perl is a subroutine, defined with the package. The first argument to the method is an object reference or a package name, depending on whether the method affects the current object or the class.

Perl provides a bless() function which is used to return a reference and which becomes an object. Perl has a special variable, @ISA which governs (method) inheritance.
Inheritance in Perl 5

    { package Animal;
    sub speak {
      my $class = shift;
      print "a $class goes ", $class->sound, "!\n";
    }
    sub name {
      my $self = shift;
      $$self;
    }
    sub named {
      my $class = shift;
      my $name = shift;
      bless \$name, $class;
    }
  }
  { package Horse;
    @ISA = qw(Animal);
    sub sound { "neigh" }
  }

PHP

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Basic object-oriented programming functionality was added in PHP 3 and improved in PHP 4. Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance. PHP 5 introduced private and protected member variables and methods, along with abstract classes and final classes as well as abstract methods and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore, PHP 5 added interfaces and allowed for multiple interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or IteratorAggregate can be used with the foreach language construct. There is no virtual table feature in the engine, so static variables are bound with a name instead of a reference at compile time.

 
class Person {
   public $firstName;
   public $lastName;
 
   public function __construct($firstName, $lastName = '') { //Optional parameter
       $this->firstName = $firstName;
       $this->lastName = $lastName;
   }
 
   public function greet() {
       return "Hello, my name is " . $this->firstName . " " . $this->lastName . ".";
   }
}
 
$he = new Person('John', 'Smith');
 echo $he->greet(); // prints "Hello, my name is John Smith."

Python

Python is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java. Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. The class statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming. Python allows programmers to define their own types using classes, which are most often used for object-oriented programming.
An object oriented program in Python

# Function defined outside the class
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1
    def g(self):
        return 'hello world'
    h = g

Ruby

Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Matsumoto has stated, "I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language" Ruby is object-oriented: every data type is an object, including classes and types that many other languages designate as primitives (such as integers, booleans, and "nil"). Variables always hold references to objects. Every function is a method and methods are always called on an object. Methods defined at the top level scope become members of the Object class. Since this class is an ancestor of every other class, such methods can be called on any object. They are also visible in all scopes, effectively serving as "global" procedures. Ruby supports inheritance with dynamic dispatch, mixins and singleton methods (belonging to, and defined for, a single instance rather than being defined on the class). Though Ruby does not support multiple inheritance, classes can import modules as mixins.

class Person
  attr_reader :name, :age
  def initialize(name, age)
    @name, @age = name, age
  end
  def <=>(person) # Comparison operator for sorting
    @age <=> person.age
  end
  def to_s
    "#@name (#@age)"
  end
end
 
group = [
  Person.new("Bob", 33), 
  Person.new("Chris", 16), 
  Person.new("Ash", 23) 
]
 
puts group.sort.reverse

Tcl-Tk

Tcl originally from "Tool Command Language" is a scripting language created by John Ousterhout. It is commonly used for rapid prototyping, scripted applications, GUIs and testing. Tcl is used on embedded systems platforms, both in its full form and in several other small-footprinted versions. Tcl 8.6 provides an OO system in Tcl core [22] The combination of Tcl and the Tk GUI toolkit is referred to as Tcl/Tk.

oo::class create fruit {
    method eat {} {
        puts "yummy!"
    }
}
oo::class create banana {
    superclass fruit
    constructor {} {
        my variable peeled
        set peeled 0
    }
    method peel {} {
        my variable peeled
        set peeled 1
        puts "skin now off"
    }
    method edible? {} {
        my variable peeled
        return $peeled
    }
    method eat {} {
        if {![my edible?]} {
            my peel
        }
        next
    }
}
set b [banana new]
$b eat               → prints "skin now off" and "yummy!"
fruit destroy
$b eat               → error "unknown command"

References

1. Object-oriented programming http://en.wikipedia.org/wiki/Object-oriented_programming
2. Loui, R. (2008). In Praise of Scripting: Real Programming Pragmatism , IEEE Computer, vol. 41, no. 7.
3. Scripting Language http://en.wikipedia.org/wiki/Scripting_language
4, 13. Kak, A. C. (2008). Scripting With Objects. Hoboken, NJ: John Wiley & Sons.
5. What is an Object? http://download.oracle.com/javase/tutorial/java/concepts/object.html
6. Classes http://en.wikipedia.org/wiki/Class_%28computer_programming%29
7. Single Inheritance http://www.inf.ufsc.br/poo/smalltalk/ibm/tutorial/oop.html
8. Multiple Inheritance http://www.java-samples.com/showtutorial.php?tutorialid=462
9. Polymorphism http://www3.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInheritancePolymorphism.html
10. Booch, G., Maksimchuk, R. A., Engle, M. W., Young, B. J., Conallen, J., & Houston, K. A. (2007). Object-Oriented Analysis and Design With Applications, Third Edition. Upper Saddle River, NJ: Addison-Wesley.
11. Don't Repeat Yourself http://www.artima.com/intv/dry.html
12, 18. Scripting http://www.tcl.tk/doc/scripting.html
14. Glue Code http://www.site.uottawa.ca:4321/oose/index.html#gluecode
15. What object-oriented Perl isn't http://www.manning.com/conway/excerpt_preface.html
16. The strength on Tcl http://equi4.com/moam/strength.html
17. Barron, D., & Barron, W. D. (2000). The world of scripting languages (August 2000 ed.). NY: John Wiley & Sons
19. The Jython Tutorial http://www.jython.org/docs/tutorial/indexprogress.html
20. Object Oriented Programming in JavaScript http://mckoss.com/jscript/object.htm
21. Open Object Rexx http://www.oorexx.org/docs/rexxref/c188.htm
22. Tcl Core http://www.tcl.tk/man/tcl8.6/TclCmd/class.htm#M13