CSC/ECE 517 Fall 2011/ch1 1g vn

From Expertiza_Wiki
Revision as of 15:19, 4 September 2011 by Vsingh3 (talk | contribs) (→‎Python)
Jump to navigation Jump to search

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).

Object-oriented programming may be seen as the design of software using a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility.

Object-oriented programming is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.[1]

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.[2]

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.

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.

The Document Object Model of HTML, XHTML, and XML documents on the Internet have bindings to the popular JavaScript/ECMAScript language. JavaScript is perhaps the best known prototype-based programming language, which employs cloning from prototypes rather than inheriting from a class. Another scripting language that takes this approach is Lua. Earlier versions of ActionScript (a partial superset of the ECMA-262 R3, otherwise known as ECMAScript) also used a prototype-based object model. Later versions of ActionScript incorporate a combination of classification and prototype-based object models based largely on the currently incomplete ECMA-262 R4 specification, which has its roots in an early JavaScript 2 Proposal. Microsoft's JScript.NET also includes a mash-up of object models based on the same proposal, and is also a superset of the ECMA-262 R3 specification.

History

Early mainframe computers (in the 1950s) were non-interactive, instead using batch processing. IBM's Job Control Language (JCL) is the archetype of language used to control batch processing.

The first interactive shells were developed in the 1960s to enable remote operation of the first time-sharing systems, and these used shell scripts, which controlled running computer programs within a computer program, the shell.

Languages such as Tcl and Lua were specifically designed as general purpose scripting languages that could be embedded in any application. Other languages such as Visual Basic for Applications (VBA) provided strong integration with the automation facilities of an underlying system. Embedding of such general purpose scripting languages instead of developing a new language for each application also had obvious benefits, relieving the application developer of the need to code a language translator from scratch and allowing the user to apply skills learned elsewhere.

Some software incorporates several different scripting languages. Modern web browsers typically provide a language for writing extensions to the browser itself, and several standard embedded languages for controlling the browser, including JavaScript (a dialect of ECMAScript) or XUL.[3]

Object Oriented features were embedded into scripting language starting with Perl 5.000 released on October 17, 1994. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular amongst programmers. Larry Wall continues to oversee development of the core language, and its upcoming version, Perl 6. Perl borrows features from other programming languages including C, shell scripting (sh), AWK, and sed. The language provides powerful text processing facilities without the arbitrary data length limits of many contemporary Unix tools, facilitating easy manipulation of text files. Perl gained widespread popularity in the late 1990s as a CGI scripting language, in part due to its parsing abilities.[4]

Another Scripting Language Ruby was conceived on February 24, 1993 by Yukihiro Matsumoto who wished to create a new language that balanced functional programming with imperative programming. 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".

At a Google Tech Talk in 2008 Matsumoto further stated, "I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language."[5]

Object Oriented Languages and Features

Benjamin C. Pierce and some other researchers view as futile any attempt to distill OOP to a minimal set of features. He nonetheless identifies fundamental features that support the OOP programming style in most object-oriented languages:

Dynamic dispatch

When a method is invoked on an object, the object itself determines what code gets executed by looking up the method at run time in a table associated with the object. This feature distinguishes an object from an abstract data type (or module), which has a fixed (static) implementation of the operations for all instances. It is a programming methodology that gives modular component development while at the same time being very efficient.

Encapsulation

Data encapsulation, sometimes referred to as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user. The user can only perform a restricted set of operations on the hidden members of the class by executing special functions commonly called methods. The actions performed by the methods are determined by the designer of the class, who must be careful not to make the methods either overly flexible or too restrictive. This idea of hiding the details away from the user and providing a restricted, clearly defined interface is the underlying theme behind the concept of an abstract data type.

The advantage of using data encapsulation comes when the implementation of the class changes but the interface remains the same. For example, to create a stack class which can contain integers, the designer may choose to implement it with an array, which is hidden from the user of the class. The designer then writes the push() and pop() methods which puts integers into the array and removes them from the array respectively. These methods are made accessible to the user. Should an attempt be made by the user to access the array directly, a compile time error will result. Now, should the designer decide to change the stack's implementation to a linked list, the array can simply be replaced with a linked list and the push() and pop() methods rewritten so that they manipulate the linked list instead of the array. The code which the user has written to manipulate the stack is still valid because it was not given direct access to the array to begin with.

The concept of data encapsulation is supported in C++ through the use of the public, protected and private keywords which are placed in the declaration of the class. Anything in the class placed after the public keyword is accessible to all the users of the class; elements placed after the protected keyword are accessible only to the methods of the class or classes derived from that class; elements placed after the private keyword are accessible only to the methods of the class.

As a convention, calling a method of an object instantiated from a class is commonly referred to as sending a message to that object.

An example of encapsulation in Ruby is as shown below.In this code, you cannot mess around with the state of its variable @value. The only way you can access it is through get & set method (get_value, set_value). This is the encapsulation

class Encapsulation
    def get_value
        @value
    end
 
    def set_value value
        @value = value
        return nil
    end
end
 
encapsulation = Encapsulation.new
encapsulation.set_value(15)
puts encapsulation.get_value

Object inheritance

In object-oriented programming (OOP), inheritance is a way to compartmentalize and reuse code by creating collections of attributes and behaviors called objects that can be based on previously created objects. In classical inheritance where objects are defined by classes, classes can inherit other classes. The new classes, known as subclasses (or derived classes), inherit attributes and behavior (i.e. previously coded algorithms) of the pre-existing classes, which are referred to as superclasses, ancestor classes or base classes. The inheritance relationships of classes gives rise to a hierarchy. In prototype-based programming, objects can be defined directly from other objects without the need to define any classes, in which case this feature is called differential inheritance.

An example of inheritance in Ruby.In Ruby, a class can only inherit from a single other class. Some other languages support multiple inheritance, a feature that allows classes to inherit features from multiple classes, but Ruby doesn't support this.

    class Mammal  
      def breathe  
        puts "inhale and exhale"  
      end  
    end  
      
    class Cat < Mammal  
      def speak  
        puts "Meow"  
      end  
    end  
      
    rani = Cat.new  
    rani.breathe  
    rani.speak  

Open recursion

A special variable (syntactically it may be a keyword), usually called this or self, that allows a method body to invoke another method body of the same object. This variable is late-bound; it allows a method defined in one class to invoke another method that is defined later, in some subclass thereof.

Classes of objects

A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.

Instances of classes

public class Bicycle{
	
    private int cadence;
    private int gear;
    private int speed;
	
    // add an instance variable for the object ID
    private int id;
    
    // add a class variable for the number of Bicycle objects instantiated
    private static int numberOfBicycles = 0;
	......
}

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle class, the instance variables are cadence, gear, and speed. Each Bicycle object has its own values for these variables, stored in different memory locations.[6]

Methods

In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property that at runtime, they have access to data stored in an instance of the class (or class instance or class object or object) they are associated with and are thereby able to control the state of the instance.[1] The association between class and method is called binding. A method associated with a class is said to be bound to the class. Methods can be bound to a class at compile time (static binding) or to an object at runtime (dynamic binding).[7]

Examples of writing method in Ruby is as shown below.[8]

def hello  
  'Hello'  
end  
#use the method  
puts hello  
  
# Method with an argument - 1  
def hello1(name)  
  'Hello ' + name  
end  
puts(hello1('satish'))  
  
# Method with an argument - 2  
def hello2 name2  
  'Hello ' + name2  
end  
puts(hello2 'talim')

Polymorphism

Abstraction

The conjunction of complex inheritance, methods, properties of an Object must be able to simulate a reality model.

Object Oriented Scripting Languages

Few of the Object Oriented Scripting languages:

AppleScript

AppleScript is a scripting language that provides direct control of scriptable applications and scriptable parts of the Mac OS. AppleScript scripting language uses an English-like terminology which may appear simple, it is a rich, object-oriented language, capable of performing complicated programming tasks. It has the concepts of classes and objects. It’s not as obvious that AppleScript also supports some fundamental OOPfeatures such as inheritance, instantiation, data encapsulation, and polymorphism.

Curl

Curl is a reflective object-oriented programming language for interactive web applications which goal is to provide a smoother transition between formatting and programming. It makes it possible to embed complex objects in simple documents without needing to switch between programming languages or development platforms. Curl is a markup language like HTML—that is, plain text is shown as text; at the same time, Curl includes an object-oriented programming language that supports multiple inheritance.

Groovy

Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform.

JavaScript

JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. It can support 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. Many people don't realize that JavaScript supports inheritance. When you write object-oriented code it instantly gives you power; you can write code that can be re-used and that is encapsulated.

Lua

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.

Object Rexx

Object REXX programming language is an object-oriented scripting language initially produced by IBM for OS/2. It is a follow-on to and a significant extension of the "Classic Rexx" language originally created for the CMS component of VM/SP and later ported to MVS,[1] OS/2 and PC DOS. Open Object Rexx includes features typical of an object-oriented language, such as subclassing, polymorphism, and data encapsulation. It is an extension of the classic Rexx language, which has been expanded to include classes (a base set of classes is supplied), objects, and methods.

Perl

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.

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. In previous versions of PHP, objects were handled like value types. The drawback of this method was that the whole object was copied when a variable was assigned or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value. 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[5] 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.

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".[9] 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", but conventionally rendered as "Tcl" rather than "TCL"; pronounced as "tickle" or "tee-see-ell"[3]) is a scripting language created by John Ousterhout.[4] 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. 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"

Conclusion

References

[1]https://developer.mozilla.org/En/Introduction_to_Object-Oriented_JavaScript