1 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 1

Data Abstraction & Encapsulation in �Object Oriented Programming

2 of 140

Abstraction- Introduction

  • Abstraction: - programmer can associate a name with a potentially complicated program fragment, which can then be thought of in terms of its purpose or function, rather than in terms of its implementation
  • Focus on the meaning, suppress the irrelevant implementation details
  • Assign names to complicated program fragment, which does some function

3 of 140

Abstraction - Advantages

1. reduces the conceptual load for the programmer

2. provides a method of fault containment by preventing the programmer from using code in an inappropriate way

3. increases the independence among program components

4 of 140

Elements of object-oriented programming:�

  • Class - user defined data type
    • includes data members and member functions
  • Objects - Data items to be manipulated
  • Objects are members of classes, that is, classes are types
  • Objects store data in fields and behavior in methods specified by their classes

5 of 140

  • Main characteristics of object-oriented programming systems:
    • Encapsulation –Wrapping up of data and member function into an object
      • Calling objects does not need to know the details how the service is accomplished
    • Inheritance-Enables a new class to reuse the state and behavior of old class
      • inherited methods can be extended using overriding facility
    • Polymorphism - enables one common interface for many implementations through dynamic method binding

6 of 140

Object oriented Languages

  • object-oriented languages include Java, C++, C#, Python, PHP, Ruby, Perl, Object Pascal, Objective-C, Dart, Swift, Scala, Common Lisp, and Smalltalk
  • The first object oriented language was Simula-67
  • Smalltalk - first “pure” object-oriented language
  • C++ (also supports procedural and data oriented programming)
  • Ada 95 (also supports procedural and data oriented programming)
  • CLOS, Scheme (also supports functional programming)

7 of 140

Fundamental OO Concepts

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Dynamic Method Binding

8 of 140

Encapsulation

  • Encapsulation - binds together the data and functions that manipulate the data
  • hides the internal state of one object from the others
  • allows the programmer to group data and the subroutines that operate on them together in one place, and to hide irrelevant details from the user
  • It only focuses on what to do

9 of 140

Encapsulation in different languages

  • Smalltalk and Ruby only allow access via object methods
  • C++, C#, Delphi or Java offer the programmer a degree of control via keywords like public and private
  • Some languages (Java, for example) allows classes to enforce access restrictions explicitly, with the private and public keyword
  • Methods may also be designed public, private, or intermediate levels such as protected which allows access from the same class and its subclasses, but not objects of a different class

10 of 140

  • Object (instance)
    • State (fields)
    • Behaviour (methods)
    • Identity

  • Class
    • code describing implementation of an object

  • Data Abstraction
  • Modularity
  • Encapsulation
  • Inheritance
  • Polymorphism

Abstraction Vs Encapsulation

11 of 140

Encapsulation-Example in C#

12 of 140

Encapsulation-Example in Java

13 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 2

Inheritance

14 of 140

INHERITANCE

  • create a new class from an existing class
  • new class is a specialized version of the existing class
  • “is-a” relation, which inherits the attributes and behaviours from its parent class
  • For example, dog is an animal. It means animal is a parent class and Dog is the child class
  • The child class “Dog” inherits the attributes like age and weight from the parent class , which is an animal

15 of 140

Inheritance

  • define a new derived or child class based on an existing parent class or superclass
  • The derived class
    • Inherits all fields and methods of the superclass,
    • Can define additional fields and methods, and
    • Can override existing fields and methods

16 of 140

Inheritance terms

  • superclass, base class, parent class: terms to describe the parent in the relationship, which shares its functionality

  • subclass, derived class, child class: terms to describe the child in the relationship, which accepts functionality from its parent

  • extend, inherit, derive: become a subclass of another class

17 of 140

Syntax of Inheritance�

  • C++

class push_button : public widget { ... }

  • Java

public class push_button extends widget { ... }

  • Ada

type push_button is new widget with ...

18 of 140

  • Methods of the base class are accessible in the derived class
  • Using scope resolution (::) in C++
  • Using the super keyword in Java or Smalltalk
  • Using explicit renaming in Eiffel

19 of 140

Inheritance - Visibility in Derived Classes

class A : public B { ... }

  • All methods have the same visibility in the derived class as in the base class

class A : protected B { ... }

  • Public and protected members of the base class become protected in the derived class. Private members remain private

class A : private B { ... }

  • All members of the base class become private in the derived class

20 of 140

20

Class Access Specifiers-In C++

determines how private, protected, and public members of base class are inherited by the derived class

  1. Public members are visible anywhere the class declaration is in scope
  2. Private members are visible only inside the class’s methods
  3. Protected members are visible inside methods of the class or its descendants

21 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 3

Encapsulation

22 of 140

Encapsulation - concepts

  • Modules
  • Classes
  • Nesting (Inner Classes)
  • Type Extension
  • Extension without inheritance

23 of 140

Modules

  • module-based languages with data hiding - Clu , Modula, Euclid
  • In Clu and Euclid, the declaration and definition (header and body) of a module always appear together
  • The header clearly states which of the module’s names are to be exported
  • If a Euclid module M exports a type T, by default the remainder of the program can do nothing with objects of type T other than pass them to subroutines exported from M

24 of 140

Modules�

  • In Modula-2, programmers have the option of separating the header and body
  • “internal” modules, in which the two parts appear together
  • In an “external” module (meant for separate compilation), the header appears in one source file and the body in another
  • There is no way to divide the header into public and private parts; everything in it is public (i.e., exported)

25 of 140

Modules

  • Ada - allows the headers and bodies of modules (called packages) to be separated, by allowing the header of a package to be divided into public and private parts
  • A type can be exported opaquely by putting its definition in the private part of the header and simply naming it in the public part:

26 of 140

Classes�

  • Private members of a base class are never visible in a derived class
  • Protected and public members of a public base class are protected or public, respectively, in a derived class
  • Protected and public members of a protected base class are protected members of a derived class
  • Protected and public members of a private base class are private members of a derived class

27 of 140

Inheritance vs. Access

private members:

char letter;

float score;

void calcGrade();

public members:

void setScore(float);

float getScore();

char getLetter();

class Grade

private members:

int numQuestions;

float pointsEach;

int numMissed;

public members:

Test(int, int);

class Test : public Grade

When Test class inherits

from Grade class using

public class access, it looks like this:

private members:

int numQuestions:

float pointsEach;

int numMissed;

public members:

Test(int, int);

void setScore(float);

float getScore();

char getLetter();

28 of 140

Inheritance vs. Access

private members:

char letter;

float score;

void calcGrade();

public members:

void setScore(float);

float getScore();

char getLetter();

class Grade

private members:

int numQuestions;

float pointsEach;

int numMissed;

public members:

Test(int, int);

When Test class inherits

from Grade class using

protected class access, it looks like this:

private members:

int numQuestions:

float pointsEach;

int numMissed;

public members:

Test(int, int);

protected members:

void setScore(float);

float getScore();

float getLetter();

class Test : protected Grade

29 of 140

Inheritance vs. Access

private members:

int numQuestions:

float pointsEach;

int numMissed;

void setScore(float);

float getScore();

float getLetter();

public members:

Test(int, int);

private members:

char letter;

float score;

void calcGrade();

public members:

void setScore(float);

float getScore();

char getLetter();

class Grade

private members:

int numQuestions;

float pointsEach;

int numMissed;

public members:

Test(int, int);

When Test class inherits

from Grade class using

private class access, it looks like this:

class Test : private Grade

30 of 140

Visibility rules in other languages

  • Eiffel
    • Derived classes can both restrict and increase the visibility of members
  • Java(Similar to C++, with the following exceptions)
    • Base classes are always public
    • Protected members are visible in derived classes & in same package

31 of 140

Visibility rules in other languages

  • Python
    • All class members are public
  • Smalltalk, Objective C
    • All methods are public. All fields are private.

32 of 140

Classes-visibility

  • Eiffel is more flexible than C++ in the patterns of visibility
  • Derived classes in Eiffel can both restrict and increase the visibility of members of base classes
  • Every method (called a feature) can specify its own export status
    • If the status is {NONE} then the member is effectively private(called secret in Eiffel)
    • If the status is {ANY} then the member is effectively public

33 of 140

Classes-visibility

  • Java, C#, C++ - declaration of public, protected, and private members
  • Java : a protected member of a Java class is visible not only within derived classes, but also within the entire package (namespace) in which the class is declared
  • C# defines protected as C++ does, but provides an additional internal keyword that makes a member visible
  • Members of a C# class are private by default

34 of 140

Inner Classes

  • Inner class is a class defined within an outer class
  • C++ and C#, allow access to only the static members of the outer class, since these have only a single instance
  • Java allows a nested (inner) class to access the members of its surrounding class
  • Each instance of the inner class must therefore belong to an instance of the outer class

35 of 140

Inner Classes In java

36 of 140

Inner class

  • If there are multiple instances of Outer, each instance will have a different n , and calls to inner.bar will access the appropriate n
  • Each instance of Inner must contain a hidden pointer to the instance of Outer to which it belongs

37 of 140

Type Extension

  • Smalltalk, Objective-C, Eiffel, C++, Java, and C# - supports a module as-type approach to abstraction
  • Class provides both encapsulation and inheritance
  • Modula-3, Ada95, Oberon, CLOS, and Fortran2003 - object-oriented extensions to languages in which modules already provide encapsulation
  • these languages provide inheritance and dynamic method binding through a mechanism for extending records

38 of 140

Extending without Inheritance

  • if the class wants to extend may not permit inheritance - in Java, labeled final; in C#, it may be sealed
  • C# 3.0 provides extension methods, which give the appearance of extending an existing class
  • An extension method must be static, and must be declared in a static class
  • Its first parameter must be prefixed with the keyword this

39 of 140

Extending without Inheritance

  • The method can then be invoked as if it were a member of the class of which this is an instance
  • No special functionality is available to extension methods
  • They cannot access private members of the class that they extend, nor do they support dynamic method binding

40 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 4

Polymorphism

41 of 140

  • ability of one object to be treated and used like another object

42 of 140

  • Polymorphism means one name many forms
  • One function behaves in different forms
  • "Many forms of a single object is called Polymorphism."
  • Ex)Your mobile phone, one name but many forms
    • As phone
    • As camera
    • As mp3 player
    • As radio

43 of 140

  • Polymorphism could be static and dynamic
  • Method Overloading is static polymorphism while, Method overriding is dynamic polymorphism
  • Overloading - more than one method having the same method name that behaves differently based on the arguments passed
  • This called static because, method to be invoked is decided at the time of compilation
  • Overriding - derived class is implementing a method of its super class
  • Call to overriden method is resolved at runtime - runtime polymorphism

44 of 140

  • method overriding - child class can use the OOP polymorphism concept to override a method of its parent class
  • allows a programmer to use one method in different ways depending on whether it’s invoked by an object of the parent class or an object of the child class
  • method overloading - a single method may perform different functions depending on the context in which it’s called
  • a single method name might work in different ways depending on what arguments are passed to it

45 of 140

Polymorphism-overriding

  • we have two classes: Person and Employee.
  • The Employee class inherits from the Person class by using the keyword extends.
  • Here, the child class overrides the parent class

46 of 140

Method overloading

47 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 5

CONSTRUCTORS & DESTRUCTORS

48 of 140

  • special mechanism in Object oriented languages to initialize an object automatically at the beginning of its lifetime

  • The lifetime of an object to be the interval during which it occupies space and can thus hold data
  • initialized when they are created
  • destructor finalize an object automatically at the end of its lifetime

Constructors

49 of 140

Constructors

  • special member function having same name of its class
  • used to initialize some valid values to the member variables
  • should be declared in the public section of the class
  • A constructor does not allocate the space for an object; it initializes (“constructs”) the object in the allocated space
  • Execution order of constructors:
    • Constructor(s) of base class(es)
    • Constructors of derived class
    • Constructor of the class itself

50 of 140

Constructor

  • doesn’t have a return type, not even void
  • can declare more than one constructor in a class. These constructor differ in there parameter list
  • If you don’t provide a constructor of your own then the compiler generates a default constructor
  • preferably be used for initialization and not for input/output operations

51 of 140

51

  • Smalltalk, Eiffel, C++, Java, and C# - allows more than one constructor for a given class
  • C++, Java, and C# - the constructors must be distinguished by their numbers and types of arguments
  • Smalltalk and Eiffel - different constructors can have different names; code that creates an object must name a constructor explicitly
  • Smalltalk resembles Eiffel in the use of multiple named constructors

52 of 140

52

  • The !! operator is Eiffel’s equivalent of new
  • Modula-3 and Oberon provide no constructors at all: the programmer must initialize everything explicitly
  • Ada 95 supports constructors and destructors (called Initialize and Finalize routines)

53 of 140

Eiffel constructors and Expanded objects

  • In Eiffel, every variable is initialized to a default value
  • For built-in types the default values are all zero
  • For references to objects, the default value is void (null)
  • For variables of expanded class types,the defaults are applied recursively to members
  • New objects are created by invoking Eiffel’s !! creation operator:

!!var.creator(args)

  • where var is a variable of some class type T and creator is a constructor for T
  • In the common case, var will be a reference, and the creation operator will allocate space for an object of class T and then call the object’s constructor

54 of 140

Syntax

class CLASSNAME

{

public:

CLASSNAME([parameter list]);

};

class A

{

int x;

public:

A(); //Constructor

};

55 of 140

Example in C++

#include<iostream.h>

#include<conio.h>

class Rectangle

{

private:

int length , breadth;

public:

Rectangle()

{

Length=5,breadth=6;

}

int area()

{

int a=(length*breadth);

cout<<“area is”<<a;

}

};

void main()

{

Rectangle r1;

r1.area();

}

56 of 140

Types of constructors

In java

In C++

1.Default Constructor

2.Parameterized Constructor

3.Copy Constructor

57 of 140

Default Constructor

  • Default constructor is the constructor which doesn't take any argument
  • called as soon as the object is created which initializes its data members
  • if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly

class_name ()

{ Constructor Definition

}

58 of 140

Default Constructor Example

  • Example :

class Cube

{

int side;

public:

Cube()

{

side=10;

}

};

int main()

{

Cube c;

cout << c.side;

}

  • Output : 10

59 of 140

Parameterized Constructor

  • constructors with parameter
  • can provide different values to data members of different objects, by passing the appropriate values as argument
  • C++ permits us to achieve this objects by passing argument to the constructor function when the object are created

60 of 140

Parameterized Constructor

class Cube

{

public:

int side;

Cube(int x)

{

side=x;

}

};

int main()

{

Cube c1(10);

Cube c2(20);

Cube c3(30);

cout << c1.side;

cout << c2.side;

cout << c3.side;

}

OUTPUT : 10 20 30

61 of 140

Copy constructor

  • creates a new object using an existing object of the same class
  • initializes each data member of newly created object with corresponding data member of existing object passed as argument
  • since it creates a copy of an existing object so it is called copy constructor
  • takes an object as argument, and is used to copy values of data members of one object into other object

62 of 140

Example

class counter

{

int c;

public:

counter(int a)

//single parameter constructor

{c=a;}

counter(counter &ob)

//copy constructor

{cout<<“copy constructor invoked”;

c=ob.c;

}

void show()

{cout<<c;

}};

void main()

{

counter c1(10);

counter c2(c1);// call copy constructor

c1.show();

c2.show();

}

63 of 140

Destructors

  • member function having same name as class
  • preceded by a tilde(~) symbol
  • executed automatically when object of a class is destroyed
  • called automatically when the object goes out of scope:

(1) the function ends

(2) the program ends

(3) a block containing temporary variables ends

(4) a delete operator is called 

64 of 140

Destructor

  • A destructor doesnt have a return type, not even void and no arguments
  • only one destructor in class
  • If you don’t provide a destructor of your own then the compiler generates a default destructor
  • used to deallocate memory for an object and declared in the public section

65 of 140

Destructors

  • To de-initialize the objects when they are destroyed
  • To clear memory space occupied by a data member

class CLASSNAME

{

……………….

public:

~CLASSNAME([parameter list]);

};

66 of 140

Example

#include<iostream.h>

#include<conio.h>

class counter

{

int id;

public:

counter(int i)

{

Id=I;

cout<<“contructor of object with id=”<<id;

}

~counter()

{

cout<<“destructor with id=”<<id;

}

};

void main()

{

counter c1(1);

counter c2(2);

counter c3(3);

cout<<“\n end of main”;

getch();

}

67 of 140

Output

constructor of object with id=1

constructor of object with id=2

constructor of object with id=3

End of main

destructor with id=3

destructor with id=2

destructor with id=1

68 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 6

STATIC DATA MEMBERS

69 of 140

  • data member that gets memory only once for the whole class no matter how many objects of a class are created
  • This common copy is shared by all objects of its class
  • The static data member are defined and declared separately
  • the static data members which are not associated with any object needs to be defined explicitly outside the class

STATIC DATA MEMBERS

70 of 140

class CLASSNAME

{

…………

static datatype DATAMEMBER;

…………………..

};

datatype CLASSNAME::DATAMEMBER=initial value ;

STATIC DATA MEMBERS

71 of 140

71

STATIC BINDING

  • The binding which can be resolved at compile time by compiler is known as static or early binding
  • The binding of static, private and final methods is compile-time
  • These method cannot be overridden and the type of the class is determined at the compile time

72 of 140

72

DYNAMIC BINDING

  • When compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding
  • Eg. Method Overriding - overriding both parent and child classes have same method and in this case the type of the object determines which method is to be executed
  • The type of object is determined at the run time so this is known as dynamic binding

73 of 140

class Human{

public static void eat()

{

System.out.println("Human is eating");

}

}

class Boy extends Human{

//Overriding method

public static void eat(){

System.out.println("Boy is eating");

}

}

STATIC BINDING IN JAVA

public class Methover{

public static void main(String args[])

{

Boy obj = new Boy();

Human ob=new Human();

Human ob1=new Boy();

obj.eat();

ob.eat();

ob1.eat();

}

} Boy is eating

Human is eating

Human is eating

74 of 140

DYNAMIC BINDING IN JAVA

class Human

{

public void eat()

{

System.out.println("Human is eating");

}

}

class Boy extends Human{

//Overriding method

public void eat(){

System.out.println("Boy is eating");

}

}

public class Methover{

public static void main(String args[])

{

Boy obj = new Boy();

Human ob=new Human();

Human ob1=new Boy();

obj.eat();

ob.eat();

ob1.eat();

}

}

Boy is eating

Human is eating

Boy is eating

75 of 140

Dynamic Method Binding

  • In inheritance a derived class D has all the members—data and subroutines—of its base class B
  • If D does not hide any of the publicly visible members of B, it is allowed that an object of class D to be used in any context that expects an object of class B
  • In Ada - a derived class that does not hide any publicly visible members of its base class. So derived class is a subtype of that base class
  • The ability to use a derived class in a context that expects its base class is called subtype polymorphism

76 of 140

Dynamic Method Binding

77 of 140

77

Static Vs Dynamic binding

    • Static method binding is more efficient
  • Static method binding:
    • The method invoked is determined by the type of the variable through which the object is accessed
    • Languages with static method binding: Simula, C++, Ada 95
  • Dynamic method binding:
    • The method invoked is determined by the type of the accessed object
    • Languages with dynamic method binding: Smalltalk, Modula 3, Java, Eiffel

78 of 140

Dynamic Method Binding

    • Two alternatives for choosing the method to call:
      • according to the types of variables (references) x and y – static method binding (will call the method of person in both cases)
      • according to the types of objects s and p to which x and y refer – dynamic method binding (will call the methods of student / professor)
  • Example (C++):

student s;

professor p;

...

person * x = &s;

person * y = &p;

x->print_mailing_label (); // ??

y->print_mailing_label (); // ??

79 of 140

Dynamic binding in C++?

80 of 140

Virtual and Non-Virtual Methods

  • Ada
    • methods take as parameter the object they are applied to
    • dynamic binding is associated not with the method but with the parameter
    • here, r needs to be declared as person'Class → dynamic binding

81 of 140

Dynamic Method Binding in C++

All objects of a given class share the same vtable.

82 of 140

Abstract Classes

  • C++

class person

{

...

public:

virtual void print_mailing_label () = 0;

...

};

    • Abstract method – virtual method with no body
      • also called pure virtual method in C++
    • Abstract class – it has at least one abstract method
      • cannot declare objects of an abstract class, just pointer
    • Interface (Java) –

class with no other members than abstract methods

83 of 140

Abstract Classes

  • Abstract method – virtual method with no body

C++

class person {

...

virtual void print_mailing_label() = 0;

...

};

Java

class person {

...

abstract void print_mailing_label();

...

};

  • An abstract class has at least one abstract method and thus cannot be instantiated
  • If all methods are abstract, then all the class does is define an interface

84 of 140

class Vehicle {

public void start() {

System.out.println("Inside start method of Vehicle");

}}

class Car extends Vehicle {

@Override

public void start() {

System.out.println("Inside start method of Car");

}}

public class DynamicBindingTest {

public static void main(String args[]) {

Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car

vehicle.start(); //Car's start called because start() is overridden method

}

}

//Output: Inside start method of Car

85 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 7

MULTIPLE INHERITANCE

86 of 140

Multiple Inheritance

allows a derived class to have multiple base classes:

class A : public B, public C { ... }

base 1

base 2

derived

87 of 140

Multiple Inheritance

  • derived class to have multiple base classes:
  • Multiple inheritance also appears in CLOS and Python
  • Simula, Smalltalk, Objective-C, Modula-3, Ada 95, and Oberon have only single inheritance
  • Java, C#, and Ruby provide a limited,“mix-in” form of multiple inheritance, in which only one parent class is permitted to have fields

88 of 140

Multiple Inheritance

  • Each base class can have its own access specification in derived class's definition:

class cube : public square,public rectSolid;

class

square

class

rectSolid

class

cube

89 of 140

#include<iostream.h>

#include<conio.h>

class student {

protected:

int rno, m1, m2;

public:

void get() {

cout << "Enter the Roll no :";

cin>>rno;

cout << "Enter the two marks :";

cin >> m1>>m2;

}};

class sports {

protected:

int sm; // sm = Sports mark

public:

void getsm() {

cout << "\nEnter the sports mark :";

cin>>sm;

}};

class result : public student, public sports {

int tot, avg;

public:

void display() {

tot = (m1 + m2 + sm);

avg = tot / 3;

cout << "\n\n\tRoll No : " << rno << "\n\tTotal : " << tot;

cout << "\n\tAverage : " << avg;

}

};

void main() {

result obj;

obj.get();

obj.getsm();

obj.display();

}

90 of 140

Potential Problem

  • Base is inherited twice by Derived 3!

Base

Base

Derived 1

Derived 2

Derived 3

91 of 140

92 of 140

92

Virtual Base Class

  • when two super classes of a class have a common base class
  • in the diagram, the TA class gets two copies of all attributes of Person class, this causes ambiguities
  • To prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class
  • This can be achieved by preceding the base class name with the word virtual

93 of 140

94 of 140

Virtual Function

  • A virtual function is a member function
    • declared within a base class
    • redefined by a derived class (i.e. overriding)

  • It can be used to support run-time polymorphism

95 of 140

Pure Virtual Functions

  • A pure virtual function has no definition relative to the base class
  • Only the function’s prototype is included

  • General form:

virtual type func-name(paremeter-list) = 0

96 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 8

Innovative features of Scripting Languages

Scoping Rules

97 of 140

Scripting Languages

  • action of writing scripts using a scripting language
  • another kind of programming
  • sequence of commands that were to be read from a file and follow in sequence
  • This style of programming frequently uses a scripting language to interconnect ‘off the shelf ‘ components that are themselves written in conventional language
  • Applications built in this way are called ‘glue applications’, and the language is called a ‘glue language

98 of 140

Types of Scripting Languages

  • Server-side Scripting Language
    • Can use huge resources of the server
    • Complete all processing in the server and send plain pages to the client
    • Reduces client-side computation overhead

99 of 140

Types of Scripting Languages

  • Client-side Scripting Language
    • Does not involve server processing
    • Complete application is downloaded to the client browser
    • Client browser executes it locally
    • normally used to add functionality to web pages e.g. different menu styles, graphic displays or dynamic advertisements

100 of 140

Different Scripting Languages

  • Active Server Pages (ASP)
    • Server side scripting language
    • Developed by Microsoft
    • Good at connecting to Microsoft databases
    • Runs only on Microsoft servers

  • Perl
    • Old UNIX language
    • Found on all Windows and Linux servers
    • Can handle text manipulation tasks
    • Excellent web scripting language

101 of 140

Different Scripting Languages

  • PHP (Hypertext Pre-Processor)
    • Especially good at connecting to MySQL
    • Very popular language
    • Runs on UNIX and Windows
    • HTML-embedded scripting language
    • Syntax looks like C, JAVA, and PERL
    • Generate Dynamic content and good User Interface
    • Server side execution

  • JSP (Java Server Pages)
    • Developed by Sun
    • Uses Java
    • Provide server-specific framework like Microsoft’s ASP

102 of 140

Different Scripting Languages

  • CGI (Common Gateway Interface)
    • Server-side solution
    • Needs to launch separate instance of application for each web request
    • Allows direct interaction with users
  • ASP.NET
    • Server-side technology to create faster, reliable and dynamic web pages
    • Supports .NET framework languages (C#, VB.NET, JScript.NET)
    • Provides flexibility to designers and developers to work separately

103 of 140

Different Scripting Languages

  • VBScript
    • Microsoft’s scripting language
    • Client side Scripting language
    • Very easy to learn
    • Includes the functionality of Visual Basic

  • JavaScript
    • Client-side Scripting language
    • Easy to use programming language
    • Enhance dynamics and interactive features of a web page
    • Allows to perform calculation, write interactive games, add special effects, customize graphic selections, create security passwords

104 of 140

Glue Languages

  • an interpreted scripting language that is designed or suited for writing glue code – code to connect software components
  • General-purpose scripting languages like Perl and Python are sometimes called glue languages, because they were originally designed to “glue” existing programs together to build a larger system

105 of 140

Scripting Language Evolution

  • Modern scripting languages have two principal sets of ancestors
    • command interpreters or “shells” and “terminal” (command-line)
      • IBM’s JCL, MS-DOS command interpreter, Unix sh and csh
    • various tools for text processing and report generation
      • IBM’s RPG, and Unix’s sed and awk

106 of 140

Scripting Language Evolution

  • From these evolved
    • Rexx, IBM’s “Restructured Extended Executor,” which dates from 1979
    • Perl, originally devised by Larry Wall in the late 1980s, and now the most widelyused general purpose scripting language
    • Other general purpose scripting languages include Tcl (“tickle”), Python, Ruby, VBScript (for Windows) and AppleScript (for the Mac)

107 of 140

Scripting Language Evolution

  • Scripting on Microsoft platforms
    • Most of the Microsoft scripting applications are based on VBScript
    • Microsoft has also developed a very general scripting interface - the web server, and the Internet Explorer browser
    • A Windows Script implementation of JScript, the company’s version of JavaScript, comes pre-installed on Windows machines
    • Many other Microsoft applications use VBScript as an extension language
    • VBScript is one of the most widely used scripting languages

108 of 140

Characteristics of scripting languages:

    • both batch and interactive use
    • economy of expression
    • lack of declarations; simple scoping rules
    • flexible dynamic typing
    • easy access to other programs
    • sophisticated pattern matching and string manipulation
    • high level data types

109 of 140

1.Both batch and interactive use

  • While a few languages (e.g. Perl) have a compiler that requires the entire source program
  • almost all scripting languages either compile or interpret line by line

2.Economy of expression

    • Two variants: some make heavy use of punctuation and short identifiers (like Perl), while others emphasize “English-like” functionality
    • Either way, things get shorter

110 of 140

3. Lack of declarations; simple scoping rules

    • While the rules vary, they are generally fairly simple and additional syntax is necessary to alter them
      • In Perl, everything is of global scope by default, but optional parameters can limit the scope to local
      • In PHP, everything is local by default, and any global variables must be explicitly imported
      • In Python, everything is local to the block in which the assignment appears, and special syntax is required to assign a variable in a surrounding scope

111 of 140

4. Flexible dynamic typing

    • In PHP, Python and Ruby, the type of a variable is only checked right before use
    • In Perl, Rexx, or Tcl, things are even more dynamic:

$a = “4”

print $a . 3 . “\n”

print $a + 3 . “\n”

Outputs the following:

43

7

112 of 140

5. Easy access to other programs

    • scripting languages generally provide more fundamental built-in support for OS functionality
    • Eg. directory and file manipulation, I/O modules, sockets, database access, password and authentication support, and network commmunications

6. Sophisticated pattern matching and string manipulation

    • Perl is the master of this, but it traces back to the text processing sed/awk ancestry
    • These are generally based on extended regular expression

113 of 140

7. High level data types

    • scripting languages provide support for sets, dictionaries, lists and tuples (at a minimum)
    • While languages like C++ and Java have these, they usually need to be imported separately
    • optimizations like arrays indexed using hash tables are quite common
    • Garbage collection is always automatic, so user never has to deal with heap/stack issues

114 of 140

Innovative Features: Scope and Names

  • Most scripting languages do not require variables to be declared
    • Perl and JavaScript permit optional declarations
    • Perl can be run in a mode (use strict ’vars’) that requires declarations
  • most scripting languages use dynamic typing
    • The interpreter can perform type checking at run time
    • Tcl is unusual in that all values—even lists—are represented internally as strings

115 of 140

Innovative Features: Scope and Names

  • Nesting and scoping
    • Scheme, Python, JavaScript provide the classic combination of nested subroutines and static (lexical) scope
    • Tcl allows subroutines to nest, but uses dynamic scope
    • Named subroutines (methods) do not nest in PHP or Ruby
    • Nested blocks are statically scoped in Perl
    • In Ruby, they are part of the named scope in which they appear
    • Scheme, Perl, Python provide for variables captured in closures
    • PHP and the major glue languages (Perl, Tcl, Python, Ruby) all have sophisticated namespace rules

116 of 140

Innovative Features: Scope and Names

  • Undeclared variables with static scope present an interesting issue: how do we know if x is local, global, or in-between (if scopes can nest)?
    • In Perl, all variables are global unless otherwise specified
    • In PHP, local unless explicitly imported
    • Ruby has only two levels: $foo is global, foo is local; @foo is instance of current object, and @@foo is instance variable of current object’s class
    • In Python, all variables are local by default, unless explicitly imported:

i=1; j=3

def outer()

117 of 140

Innovative Features: Scope and Names

  • Scope in Python
    • By default, there is no way for a nested scope

  • R has an interesting convention:
    • Normal assignment puts value into the local variable:

i <- 4

    • Superassignment puts value into whatever variable would be found under normal (static) scoping rules:

i <<- 4

118 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 9

Innovative features of Scripting Languages

Strings and Pattern Matching

119 of 140

Innovative Features : String& Pattern matching

  • Regular expressions are present in many scripting languages and related tools employ extended versions of the notation
    • extended regular expressions in sed and awk, Perl, Tcl, Python, and Ruby
    • grep, the stand-alone Unix is a pattern-matching tool

120 of 140

Innovative Features : String& Pattern matching

  • In general, two main language groups
    • The first group includes awk, egrep (the most widely used of several different versions of grep), the regex routines of the C standard library, and older versions of Tcl
      • These implement REs as defined in the POSIX standard
    • Languages in the second group follow the lead of Perl, which provides a large set of extensions, sometimes referred to as “advanced REs”

121 of 140

Pattern matching-POSIX RE

  • Basic operations are familiar:

/ab(cd|ef)g*/ - Matches abcd, abcdg, abefg, abefgg, etc

  • Other quantifiers:
    • ?: 0 or 1 repetitions
    • +: 1 or more repetitions
    • {n}: exactly n repetitions
    • {n,}: at least n repetitions
    • {n,m}: between n and m repetitions
    • ^ and $ force the match to be at the beginning or end of the line
    • Brackets can indicate a character class: [aeiou] - any vowel
    • Ranges: [0-9]
    • A dot . matches any single character

122 of 140

Pattern matching-Extended RE

  • Perl adds on to this extensively
  • Example:

$_ = “albatross”;

if (/ba.*s+/) … #true

if (/^ba.*s+/) … #false - no match at start

  • =~ tests if it matches, !~ tests if it does not (or defaults to checking against $_, if not specified)
  • Substitution is done by s///:

$foo = “albatross”;

$foo =~ s/lbat/c; #now across

123 of 140

Regular expression escape sequences in Perl

124 of 140

Pattern matching-Greedy and Minimal Matches

  • The usual rule for matching in REs is sometimes called “left-most longest”:
  • when a pattern can match at more than one place within a string, the chosen match will be the one that starts at the earliest possible position within the string
  • In the string abcbcbcde, for example, the pattern Greedy and minimal matching/(bc)+/ can match in six different ways:
  • The third of these is “left-most longest,” �also known as greedy
  • “left-most shortest” is known as minimal match

125 of 140

Pattern matching-Greedy Matches

  • Other options:
    • *? matches the smallest number of instances of the preceeding subexpression
    • +? matches at least one instance
    • ?? matches either 0 or 1 instance, with a preference for 0

126 of 140

Implicit capture of prefix,match, and suffix

  • For simple matches, Perl also provides pseudo variables named $‘, $&, and $’.

127 of 140

KTU CS403 Programming Paradigms

Module - 5 Part 10

Innovative features of Scripting Languages

Data Types & Objects orientation

128 of 140

Innovative Features: Data Types

  • scripting languages don’t generally require the declaration of types for variables
  • Most perform run-time checks to make sure that values are never used in inappropriate ways
  • Some languages (e.g., Scheme, Python, and Ruby) are relatively strict about this checking
    • When the programmer wants to convert from one type to another, it must say so explicitly
  • Perl (and likewise Rexx and Tcl) takes the position that programmers should check for the errors they care about
    • in the absence of such checks the program should do something reasonable

129 of 140

Innovative Features: Data Types-Numeric Types�

  • numbers in JavaScript are always double-precision floating point
  • In Tcl they are strings, converted to integers or floating-point numbers (and back again) when arithmetic is needed
  • PHP uses integers plus double-precision floating point
  • Perl and Ruby add arbitrary precision (multiword) integers, sometimes known as bignums
  • Python has bignums, too, plus support for complex numbers
  • Scheme has all of the above,plus precise rationals, maintained as numerator, denominator pair
  • Fixnum and Bignum are both descendants of Integer

130 of 140

Innovative Features: Data Types

If we type the following in Ruby,

a = "4"

print a + 3, "\n"

we get the following message at run time: “In ‘+’: failed to convert Fixnum intoString (TypeError).”�In Perl is much more forgiving. �$a = "4";

print $a . 3 . "\n"; # ’.’ is concatenation

print $a + 3 . "\n"; # ’+’ is addition

//prints 43 and 7.

131 of 140

Innovative Features: Data Types

  • Before we can Explicit conversion in Ruby subscript, we must make sure that it refers to an array:

a = [] # empty array assignment

a[3] = "1"

  • If the first line were not present ,the second line would have generated an “undefined local variable” error
  • cannot concatenate a string and nil, nor can we add them
  • concatenation, and a[4] may be nil
  • print a[3] + String(a[4]), "\n"
  • addition, print Integer(a[3]) + Integer(a[4]), "\n"

132 of 140

Innovative Features: Data Types-Composite Types

  • heavy emphasis is on mappings (also called dictionaries, hashes, or associated arrays)
  • Perl, the oldest of the widely used scripting languages, inherits its principal composite types—the array and the hash—from awk
  • It also uses prefix characters on variable names as an indication of type:

$foo is a scalar � @foo is an array;� %foo is a hash;� &foo is a subroutine; and� Plain foo is a filehandle or an I/O format , Depending on context

133 of 140

  • Ordinary arrays in Perl are indexed using square brackets and integers starting Perl arrays with 0

  • Hashes are indexed using curly braces and character string name

Innovative Features: Data Types-Composite Types

134 of 140

  • Tuples in Python
  • In addition to arrays (lists) and hashes (dictionaries),Python provides two other composite types: tuples and sets
  • A tuple - an immutable list (array). The initializer syntax uses parentheses rather than brackets:

crimson = (0xdc, 0x14, 0x3c) # R,G,B components

  • They also form the basis of multiway assignment:

a, b = b, a # swap

Innovative Features: Data Types-Composite Types

135 of 140

  • Arrays and hashes in Python and Ruby
  • Python and Ruby, like Perl, provide both conventional arrays and hashes
  • They use square brackets for indexing and distinguish between array and hash initializers (aggregates) using bracket and brace delimiters,respectively:

  • This is Ruby syntax; Python uses : in place of =>

Innovative Features: Data Types-Composite Types

136 of 140

  • Sets in Python
  • Python sets are like dictionaries that don’t map to anything of interest, but simply serve to indicate whether elements are present or absent. Unlike dictionaries, they also support union, intersection, and difference operations:

Innovative Features: Data Types-Composite Types�

137 of 140

  • Context - refers to information about how a value will be used
  • In C, for example, one might say that in the declaration

double d = 3;

  • the 3 on the right-hand side occurs in a context that expects a floating-point number. The C compiler coerces the 3 to make it a double instead of an int

Innovative Features: Data Types-Composite Types

138 of 140

  • the assignment operator (=) provides a scalar or list context to its right-hand side based on the type of its left-hand side
  • This type is always known at compile time , because the left-hand side is a name and its prefix character is either a dollar sign ($),implying a scalar context, or an at (@) or percent (%) sign, implying a list context

$time = gmtime();

  • Perl’s standard gmtime() library function "Sun Aug 17 15:10:32 2008"

@time_arry = gmtime();

  • same function will return (39, 09, 21, 15, 2, 105, 2, 73), an 8-element array indicating seconds, minutes, hours, day of month, month of year(with January = 0), year (counting from 1900), day of week (with Sunday = 0), and day of year

139 of 140

    • Perl 5 has features that allow one to program in an object-oriented style
    • PHP and JavaScript have cleaner, more conventional-looking object-oriented features
      • both allow the programmer to use a more traditional imperative style
    • Python and Ruby are explicitly and uniformly object-oriented
    • Perl uses a value model for variables; objects are always accessed via pointers
    • In PHP and JavaScript, a variable can hold either a value of a primitive type or a reference to an object of composite type
      • In contrast to Perl, however, these languages provide no way to speak of the reference itself, only the object to which it refers

Innovative Features: Object Orientation

140 of 140

    • Python and Ruby use a uniform reference model
    • Classes are themselves objects in Python and Ruby, much as they are in Smalltalk
    • They are types in PHP, much as they are in C++, Java, or C#
    • Classes in Perl are simply an alternative way of looking at packages (namespaces)
    • JavaScript, remarkably, has objects but no classes
      • its inheritance is based on a concept known as prototypes
  • Python and Ruby are explicitly object-oriented.
  • Both employ a uniform reference model for variables.Both PHP and JavaScript are more explicitly object oriented

Innovative Features: Object Orientation