Comparison of Object-Oriented Progamming Languages
Comparative Programming Paradigms [COPPCO801]

Thomas D. Devine

http://www.noucamp.org

thomas.devine@lyit.ie


Contents


List of Figures

Document Information

This document has been produced primarily from the notes from a pre-semester subject Comparative Programming. The sources Big C++ [1], Learning Java [4], Object-Oriented Software Construction [2], the Java Tutorials [3] and the Python Website (http://www.python.org/) were also used. There is no requirement for you to purchase these or any other book. These notes will be sufficient for any assignments and examination assessment for this module.

Criteria of Object-Oriented Programming Languages

Java Primer

You should be well primed by now!

Java Object-Oriented Programming

Introduction

Java is an OOP language and you need an understanding of OO concepts to understand Java. The four key principles of OOP are:-

Abstraction

To process something from the real world on a computer, we have to extract the essential characteristics of it. The data representing these characteristics are how we will process that thing in a system.

For example, think of a car. The Vehicle Registration office system will record - the car registration; chassis number; current owner, tax due date and so on. A garage computer system will record - registration number; work description; billing information; owner and so on. Finally, the car owner's budgeting system may record - car description; service history, petrol consumption; mileage and so on.

These are all examples of data abstractions. Data abstraction is the process of removing the unimportant details of an object, so that only relevant details remain.

Abstraction of objects is something we all do everyday. We look at an object or thing and extract different characteristics from it. For example, take a sheep (let’s call her Daisy). A farmer may look at Daisy and extract the following data - is she healthy; size; weight; etc. A clothes designer might extract the data -- wool type; wooly jumper; etc. And finally a biologist may extract data such as heart; lungs; brain; liver; etc.

Encapsulation

The next step beyond abstraction is the recognition that, equally important as data, are the operations that are performed on it. Encapsulation simply means that there should be a way to associate the two together and treat them as a single unit. In OOP data and functions (methods) should be bundled together in a class/object. So you can say "here is the Car object and these are the functions (methods) that can be applied to it".

Encapsulation is one of the first things you note about OOP when you look at it first. It's how data and the methods that can be applied to it are bundled together in a class. Listing CD.java shows encapsulation.

*****************************************************************
Listing: CD.java
*****************************************************************

class CD
{
   /* data */
   private String CDDB; 
   private String artist; 
   private String title;

   /* methods */
   public String getCDDB(){ 
      return(CDDB);
   }
   public void setCDDB(String CDDB){ 
      this.CDDB=CDDB;
   }
   public String getArtist(){ 
      return(artist);
   }
   public void setArtist(String artist){ 
      this.artist=artist;
   }
   public String getTitle(){
      return (title)
   }
   public void setTitle(String title){ 
      this.title=title;
   }
   public void printDetaits(){
      System.out.println("CDDB :"+getCDDB()); 
      System.out.println("Artist:"+getArtist());
      System.out.println("Title :"+getTitle()); 
   }
}
*****************************************************************
*****************************************************************
Here we can see an abstraction of a music CD in the form of the class CD. It has 3 data values CDDB, artist, and title. It also has 7 methods that are associated with the data, so the methods are encapsulated with the data inside the CD class.

Classes

A class is a template describing data and its methods grouped together to represent something, like the CD class earlier. Listing Fruit.java shows an example.

*****************************************************************
Listing: Fruit.java
*****************************************************************

class Fruit
{
   int grams;
   int caloriesPerGram;

   int totalCalories(){
      return(grams*caloriesPerGram); 
   }
}
*****************************************************************
*****************************************************************
You need to create an object from the class before you can invoke(call) the methods. For example:-
Fruit apple = new Fruit();
apple.grams=50;
apple.caloriesPerGram=2;
System.out.println("caloriesPerGram of an apple ="+apple.totalCalories());
All objects in Java (like apple above) are always accessed through memory references all the time. This is called indirect addressing.

Constructors

When you create an object variable like apple above you can't actually do anything with it until it points to an object instance. In the code above we created an object variable called apple with the code:-
Fruit apple
and then we created a Fruit object with the code:-
.... = new Fruit();
In summary, apple is an object instance of the class Fruit():-
Fruit apple = new Fruit();
The code new Fruit() is a special kind of method called a constructor. Constructors always have the same name as the class, in this case Fruit. Listing Fruit.java is a rewrite of the Fruit class with a constructor explicitly added.

*****************************************************************
Listing: Fruit.java
*****************************************************************

class Fruit
{
   int grams;
   int caloriesPerGram;
   public Fruit()	//constructor
   {
      grams=0; 
      caloriesPerGram=0;
   }
   int totalCalories(){
      return(grams*caloriesPerGram);
   }
}
*****************************************************************
*****************************************************************
In the listing the constructor will be called when the any object is created using code like:-
Fruit apple = new Fruit();
Here the constructor Fruit() is called. In the example the class variables(attributes) are initialised and this is typically what happens in most constructors.

Inheritance

Inheritance occurs when a class adopts or adapts the data and methods of a base or parent class. That creates a hierarchy. Inheritance is one of the concepts of Object-Oriented Programming. Listing Fruit.java & Apple.java shows a new class, Apple, inherits from the Fruit class.

*****************************************************************
Listing: Fruit.java Apple.java
*****************************************************************

class Fruit
{
   int grams;
   int caloriesPerGram;

   public Fruit(){
      grams=0; 
      caloriesPerGram=0;
   }
   int totalCalories(){
      return(grams*caloriesPerGram);
   }
}

class Apple extends Fruit 
{
   String variety;

   void setVariety(String v){ 
      variety=v;
   }
   String getVariety(){
      return (variety)
   }
}
*****************************************************************
*****************************************************************
 

The Apple class inherits from the base class Fruit by using the syntax:-

class Apple extends Fruit
The Apple class can then be used as follows:-
Apple gs = new Apple();
gs.setVariety("granny smith");
System.out.println(gs.getVariety()); // prints "granny smith"
Also, by virtue of inheritance Apple inherits methods from the Fruit class. For example the following is valid:-
Apple gs = new Apple(); 
System.out.println(gs.totalCalories());  //prints 0

Interfaces

Interfaces are in Java to allow a class to say it behaves like some other class. An interface is a skeleton of a class showing the methods the class will have when someone implements it. An interface looks a bit like a class but it's not. It doesn't have any behaviour, it's more like promised behaviour. An interface that we have seen in Event Handling is the ActionListener interface. Listing ActionListener shows it.

*****************************************************************
Listing: ActionListener
*****************************************************************

public interface ActionListener
{
   public void actionPerformed(ActionEvent event);
}
*****************************************************************
*****************************************************************
The interface has only one method - actionPerformed() - that must be included in any class that implements the interface. Listing framePanel.java shows how it is implemented.

*****************************************************************
Listing: framePanel.java
*****************************************************************

public class framePanel extends JPanel implements ActionListener
{
   . . .
   . . .
   public void actionPerformed(ActionEvent e)
   {
      //code to do something AMAZING here!!
   }
}
*****************************************************************
*****************************************************************
The framePanel class promises to implement the ActionListener interface. Therefore, it is obliged to include ActionListener's method actionPerformed() in its class code. Interfaces are a way of saying "You need to plug some code in here for this thing to fully work".

Polymorphism

Polymorphism - its sounds complicated but it isn't. It's actually Greek for "many shapes". But I promise not to speak Greek here. In programming it means using the same one name to refer to different methods. In Java there are two types of polymorphism.

Method Overriding

In the author's opinion this is true polymorphism. Listing Polymorphism illustrate the concept here.

*****************************************************************
Listing: Polymorphism
*****************************************************************

class Animal
{
   public Animal(){
   }
   public void speak() // not coded here - coded in subclasses
   {
   }
}

class Dog extends Animal
{
   public Dog() {}
   public void speak()
   {
      System.out.println("WOOF!");
   }
}

class Cat extends Animal
{
   public Cat() {}
   public void speak()
   {
      System.out.println("MEOW!");
   }
}

class Fish extends Animal
{
   public Fish() {}
}

public class AnimalTalk
{
   public static void main(String args[]){
      System.out.println("***Normal method calling***");
      Dog dog = new Dog(); 
      Cat cat = new Cat(); 
      dog.speak();
      cat.speak();

      System.out.println("***Polymorphism***");
      Animal animal; 
      animal=dog;
      animal.speak(); 
      animal=cat;
      animal.speak();
   }
}
*****************************************************************
*****************************************************************
Run this code to see what it does. In the program there is parent class called Animal and three subclasses Dog, Cat, and Fish that inherit from Animal.

The code below :-

System.out.println("***Normal method calling***");
Dog dog = new Dog(); 
Cat cat = new Cat(); 
dog.speak();
cat.speak();
creates two objects - dog (an instance of Dog) and cat (an instance of Cat). Then each objects' speak() method is called and it predictably prints WOOF! for the dog and MEOW! for the cat.

Here's the polymorphism. A third object - animal - was declared but wasn't given a value intially:-

System.out.println("***Polymorphism***");
Animal animal;	// declared but not initialised
Eventually in the code (below) animal is given a value. It is initialised using the dog object which means animal is the same as the dog object. When we call the method speak() it prints WOOF!. This is polymorphism. Polymorphism is when the method called for the object animal depends on its value at run-time (when the program is running NOT when it is compiled).

animal=dog;
animal.speak();   //prints WOOF! 
animal=cat;
animal.speak();   //prints MEOW!
Finally above, animal is initialised again using the cat object which means animal is the same as the cat object. When we call the method speak() it prints MEOW! Again, the method for the object animal is resolved at run-time. This is polymorphism!

What about the fish?? Come on everybody knows fish can't speak!

Method Overloading

The really easy kind of polymorphism is called overloading. It means a class can have the same name for many different (but related) methods. The methods however have different signatures (or prototypes). For example:-
public int printSum(int num1);
public int printSum(int num1,int num2);
public int printSum(int num1,int num2,int num3);
These methods have the same method name but have differing numbers of parameters passed to them - overloading methods. Listing Method Overloading demonstrates a program that uses these methods. Run this code.

*** Method Overloading ***

class Sum
{
   public Sum() {}
   public int printSum(int num1){
      return num1;
   }
   public int printSum(int num1,int num2) {
      return num1+num2;
   }
   public int printSum(int num1,int num2,int num3){
      return num1+num2+num3; 
   }
   public class Overload
   {
      public static void main(String args[]){
         System.out.println("***Calling override methods***"); 
         Sum sum = new Sum();
         System.out.println(sum.printSum(1)); 
         System.out.println(sum.printSum(1,2)); 
         System.out.println(sum.printSum(1,2,3));
      }
   }
}

Python Primer

Background

What is Python?

Python is an easy to learn, powerful object-oriented programming language created by Guido van Rossum. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site, and can be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation.

These tutorials introduce the reader informally to the basic concepts and features of the Python language and system. For a description of standard objects and modules, see the Python Library Reference document. The Python Reference Manual gives a more formal definition of the language. There are also several books covering Python in depth.

This tutorial is not comprehensive and does not cover every single feature. It introduces some of Python's features, and will give you a good idea of the language's flavor and style. After reading it, you will be able to read and write simple Python programs, and you will be ready to learn more about Python.

Some Python Features:-

Gentle Introduction

These notes are created from the Python Tutorial written by Guido van Rossum (Mr.Python!).

Start the interpreter and wait for the primary prompt:-

Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) 
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>>
As you run through this document think of how easy/difficult these tasks are in other programming languages. I promise Python will make an impression on you. If it doesn't - you and C++ deserve each other!!!

Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will output the value. The operators +, -, * and / work just like in most other languages and parentheses can be used for grouping. For example:-

>>> 2+2
4
>>>
>>> # This is a comment
>>>
>>> (50-5*6)/4
5
>>>
>>> 7/3       # Integer division is rounded
2
>>>
Like in Java/C, the equal sign ("=") is used to assign a value to a variable:-
>>> width=10
>>> height=10
>>> length=10
>>> width*length*height
1000
>>>
A value can be assigned to several variables simultaneously:-
>>> width=height=length=10
>>> width*height*length
1000
>>>
There is full support for floating point. Operators with mixed type operands convert the integer operand to floating point:-
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
>>>

Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:-
>>> "hello,world!"
'hello,world!'
>>>
String literals can span multiple lines in several ways. Continuation lines can be used, with a backslash as the last character on the line indicating that the next line is a logical continuation of the line:-
>>>
>>>poem="I WANDERED lonely as a cloud\n\
That floats on high o'er vales and hills,\n\
When all at once I saw a crowd,\n\
A host, of golden daffodils;\n"
>>>
>>> print poem
I WANDERED lonely as a cloud
That floats on high o'er vales and hills,
When all at once I saw a crowd,
A host, of golden daffodils;

>>>
Strings can be concatenated (glued together) with the + operator, and repeated with *:-
>>>
>>> print "hello,"+"world!"
hello,world!
>>>
>>> print "hello\n"*3
hello
hello
hello

>>>
Strings can be subscripted (indexed) like in C/Java, the first character of a string has subscript (index) 0. A character is simply a string whose size is one:-
>>>
>>> greeting="Happy Birthday"
>>> greeting[0]
'H'
>>> greeting[1]
'a'
>>>
Substrings can be specified with the slice notation - two indices separated by a colon:-
>>>
>>> greeting[0:3]
'Hap'
>>> greeting[6:]
'Birthday'
>>> greeting[:5]
'Happy'
>>>
Assigning a value to an indexed position in the string results in an error:-
>>>
>>> greeting[0]="N"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>>
Finally for now, the built-in function len() returns the length of a string:-
>>>
>>> len(greeting)
14
>>>

Lists

Python has a number of compound data types, used to group together values. The most versatile is the list (like an array), which can be written as a list of comma-separated values (items) between square brackets. The list items need not all have the same type:-

>>>
>>> numbers = [1,2,"three","four",5]
>>> print numbers[0]
1
>>>
>>> print numbers[3]
four
>>>
>>> len(numbers)
5
>>>

Control Flow

if statement

The if statement:-

>>>
>>> age=21
>>> if(age>17):
...     print "you can vote"
... else:
...     print "you can't vote"
...
>>>
Above, we set the age to 21. Note the if statement has a colon(:) at the end of the line and that the print statements MUST be tab indented. Python forces you to indent your if statements amongst others. At last, a language that FORCES indentation. That'll teach yous!!

There can be zero or more else parts. The keyword elif is short for else if, and is useful to avoid excessive indentation :-

>>> age=17
>>> if(age>17):
...     print "you can vote"
... elif(age>16):
...     print "you can drive"
... else:
...     print "can't vote or drive yet"
...
>>>

switch statement

An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages. For example:-
>>> number=3
>>> if(number==1):
...     print "one"
... elif(number==2):
...     print "two"
... elif(number==3):
...     print "three"
...
three
>>>

for statement

The for statement in Python differs a bit from what you may be used to in C or Java. Rather than giving the user the ability to define both the iteration step and halting condition, Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example :-
>>>
>>> numbers = [1,2,3,4,5]
>>> for x in numbers:
...     print x
...
1
2
3
4
5
>>>
>>>
Here's another example:-
>>> greeting="hello"
>>>
>>> for x in greeting:
...     print x
...
h
e
l
l
o
>>>

The range() function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions:-
>>> range(5)
[0, 1, 2, 3, 4]
>>>
>>> range(5,10)
[5, 6, 7, 8, 9]
>>>
The range() function can be combined with the for() statement to give:-
>>> for x in range(5):
...     print x*x
...
0
1
4
9
16
>>>

while statement

The while statement executes as long as the condition remains true. In Python, like in C, any non-zero integer value is true; zero is false:-
>>> x=0
>>> while(x<5):
...     print x
...     x=x+1
...
0
1
2
3
4
>>>

break and continue statements

The break statement, like in C, breaks out of the enclosing for or while loop. The continue statement, also borrowed from C, continues with the next iteration of the loop.

pass statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:-
>>> x=0
>>> if(x==0):
...     pass	# do nothing
...
>>>

Functions

The keyword def introduces a function definition. It must be followed by the function name and the parenthesised list of formal parameters. The statements that form the body of the function start at the next line, and must be indented. Below we create a function called sqr() and call it :-
>>> def sqr(n):
...     return(n*n)
...
>>>
>>> # now call the function we created
>>> sqr(2)
4
>>>
The return statement returns a value from a function. return without an expression argument returns None. Here's another simple function :-
>>> def printText(text,x):
...     for i in range(x):
...             print text
...
>>>
>>> # call the function
>>> printText("hello",3)
hello
hello
hello
>>>

More on lists

Below we create a new list (names) with some of the Python's in it:-
>>> names=["john","eric","michael"]
>>>
>>> names
['john', 'eric', 'michael']
>>>
The list data type has some very useful methods. Below we use these methods:-
>>> names.append("terry")
>>> names
['john', 'eric', 'michael', 'terry']
>>>
>>>
>>> names.append("George")   # who?
>>> names
['john', 'eric', 'michael', 'terry', 'George']
>>>
>>>
>>> names.remove("George")
>>> names
['john', 'eric', 'michael', 'terry']
>>>
>>>
>>> names.index("eric")
1
>>>
>>>
>>> names.sort()                    # wow!
>>> names
['eric', 'john', 'michael', 'terry']
>>>
>>>
>>> names.reverse()                 # too much!
>>> names
['terry', 'michael', 'john', 'eric']
>>>
>>>
>>> names.pop()
'eric'
>>> names.pop()
'john'
>>> names.pop()
'michael'
>>> names.pop()
'terry'
>>> names
[]
>>>

Modules

If you quit from the Python interpreter and enter it again, the definitions you have made are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you've written in several programs without copying its definition into each program.

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module.

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Use your favorite text editor (vi?) to create a file called myFunctions.py in the current directory with the following contents:-

def sqr(n):
    return(n*n)

def cube(n):
    return(n*n*n)

def factorial(n):
    if(n>1):
        return(n*factorial(n-1))
    else:
        return(1)
Now run the Python interpreter again and import the module:-
>>> import myFunctions
>>>
This does not enter the names of the functions defined in myFunctions.py directly in the current session; it only enters the module name myFunctions. Using the module name you can access the functions:-
>>> myFunctions.sqr(3)
9
>>> myFunctions.cube(3)
27
>>> myFunctions.factorial(3)
6
>>>
>>> myFunctions.__name__
'myFunctions'
>>>
Notice how the global variable __name__ above stores the name of the module.

There is a variant of the import statement that imports functions from a module directly. For example:-

>>> from myFunctions import sqr, cube
>>>
>>>
>>> sqr(2)
4
>>> cube(3)
27
>>> factorial(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'factorial' is not defined
>>>
Notice how the factorial() function failed because it wasn't imported. Here is a variant to import all functions that a module defines:-
>>> from myFunctions import *
>>>

Standard Modules

Python comes with a library of standard modules (see the Python Library Reference). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in.

One particular module deserves some attention - sys - which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:-

>>> import sys
>>>
>>> sys.ps1
'>>> '
>>>
>>> sys.ps2
'... '
>>>
>>>
>>> sys.ps1="C:\>"
C:\>
C:\>sys.ps1=">>> "     # reset default prompt
>>>
The variable sys.path is a list of strings that determine the interpreter's search path for modules. Here you can see the search path for my Linux PC:-
>>> sys.path
['', '/usr/lib/python25.zip', '/usr/lib/python2.5']
>>>

Input and Output

Keyboard input

Finally, we can input data from the keyboard. Below we can use the raw_input() function to read data:-
>>> name=raw_input("input your name:")
input your name:tom
>>> print name
'tom'
>>>
>>> age=raw_input("input your age:")
input your age:18
>>> print age      # notice that age is a string
'18'          
>>>
>>> age=int(age)   # converts age to int
>>> age
18
>>>

Simple output

Below are some useful ways of outputing data:-
>>> print age
18
>>> print "i am",age
i am 18
>>>
>>> print "my name is",name
my name is tom
>>>
>>>
>>> str(age)     # prints age as a string
'18'
>>>

Reading and Writing Files

The function open() opens & returns a file object, readline() reads a single line from a file object and close() closes the file object. Here's how we can use these functions to read lines from the myFunctions.py module:-
>>> f=open('myFunctions.py','r')
>>> f.readline()  # readline() reads newline(\n) and tab(\t) characters too
'def sqr(n):\n'
>>> f.readline()
'\treturn(n*n)\n'
>>> f.readline()
'\n'
>>> f.close()
Let's create a new file called myname.txt that contains my name and then read it:-
>>> f=open('myname.txt','w')  # (w)rite mode creates a new or erases existing file
>>> f.write("tom")
>>> f.close()
>>>
>>> f=open('myname.txt','r')   
>>> f.readline()              # super or what!
'tom'
>>> f.close()

Python Object-Oriented Programming

These notes are created using some of the material from the article Object Oriented Programming With Python written by Icarus and can be found via the Python website. However, I come across as someone with an serious obsession with snakes - read on.

Python was built from the ground up as an object-oriented language, and so provides built-in constructs that make it simple for developers to structure code for maximum reusability. Python's dynamic typing, which automatically recognizes objects like numbers, strings and lists, and negates the need to declare variable types and sizes, offers an advantage not found in languages like C or Java, while automatic memory allocation and management, together with a vast array of pluggable libraries and high-level abstractions, complete the picture.

We'll be covering most of the basics - classes, objects, attributes and methods - and a couple of the essential concepts - constructors, inheritance, and polymorphism.

Basic Terminology

If you know basic OOP terminology like classes and objects, skip this section.

In Python, a class is simply a set of program statements which perform a specific task. A typical class definition contains both variables and functions, and serves as the template from which to spawn specific instances of that class.

These specific instances of a class are referred to as objects. Every object has certain characteristics, or data, and certain pre-defined functions or methods. This data and methods of the object correspond directly with the variables and functions within the class definition.

Once a class has been defined, Python allows you to spawn as many instances of the class as you like. Each of these instances is a completely independent object, with its own properties and methods, and can thus be manipulated independently of other objects.

Classes also help you keep your code modular - you can define a class in a separate file, and include that file only in the programs where you plan to use the class.

A Python Class

Below is a simple Python class ( Listing Python Class):-

*** Python Class ***

class Snake:
   def eat(self):
      print "munch! munch!"
   def sleep(self):
      print "zzzzzzzzzz!"
Every class definition begins with the keyword class followed by the class name. All functions within the class are indented. Once we've got a class create a object with the code below:-

>>>
>>> monty=Snake()       # creates a object called monty
>>>

Let's call a few object functions:-

>>>
>>> monty.eat()         # time to feed monty
munch! munch!
>>>
>>> monty.sleep()       # now sleep
zzzzzzzzzz!
>>>

The statements inside a class definition will usually be function definitions. Above we have the functions eat and sleep. Do you like what you see so far? Listing Java Class is the equivalent code in Java. Don't get me wrong, I like Java, but the Python code is quite neat.

*** Java Class ***

class Snake
{
   public void eat()
   {
      System.out.println("munch! munch!");
   }
   public void sleep()
   {
      System.out.println("zzzzzzzzzz!");
   }
}

public class monty
{
   public static void main(String args[])
   {
      Snake monty=new Snake();
      monty.eat();
      monty.sleep();      
   }
}
Let us add a class variable name to the class and set it using the setName() function (Listing Python Class With Funcion).

*** Python Class With Function ***

class Snake:
   def eat(self):
      print "munch! munch!"
   def sleep(self):
      print "zzzzzzzzzz!"
   def setName(self,name):
      self.name=name
>>> monty=Snake()
>>> monty.setName("Sammy")
>>> print monty.name
Sammy
>>>
Above, the function setName() sets the class variable name to "Sammy". The class variable name is refered to as self.name.

The self variable has a lot to do with the way class functions work in Python. When a class function is called, it is passed a reference to the object that is calling it. This reference is passed as the first argument to the method, and is represented by the self variable.

When the object monty calls the function setName() a reference of the object is passed to the function along with the name parameter ("Sammy"). This reference is then used to set the name variable belonging to that specific object.

I hope you follow this. To illustrate this look at this code:-

>>> boa=Snake()
>>> Snake.setName(boa,"Bobby")
>>> print boa.name
Bobby
>>>
>>>
Here you can see we call the function setName() directly and pass it a reference to the object.

Constructors

A constructor in a class is implemented as the __init__() function. As is normal in other OOP languages a constructor is used to initialise class variables or execute class functions. Let's add a constructor to the Snake class (Listing Python Constructor).

*** Python Constructor ***

class Snake:
   def __init__(self):           # the constructor
      self.name="Sammy"
      self.type="Python"
      print "A new snake"
   def setName(self,name):
      self.name=name
   def setType(self,type):
      self.type=type
   def whoami(self):
      print "I am " + self.name + " your pet " + self.type
We initialise the name and type class variables and print a simple message. Let's see this and the other methods in action:-

>>> monty=Snake()
A new snake
>>>
>>> monty.whoami()
I am Sammy your pet Python
>>>

Just like Java, Python constructors can have parameters too. See Listing Python Constructor 2:-

*** Python Constructor 2 ***

class Snake:
   def __init__(self,name,type):
      self.name=name
      self.type=type
      print "A new snake"
   def whoami(self):
      print "I am " + self.name + " your pet " + self.type
>>> monty=Snake("Sammy","Python")
A new snake
>>> monty.whoami()
I am Sammy your pet Python
>>>

Inheritance

One of the BIG advantages of OOP is that it allows you to reuse existing classes and add more functionality to them. This is inheritance. By creating a class which inherits from an existing class you can reduce development time drastically. (Listing Python Inheritance)shows inheritance:-

*** Python Inheritance ***

class Snake:
   def __init__(self):
      self.name=""
   def setName(self,name):
      self.name=name

class Cobra(Snake):                     # Cobra inherits from a Snake
   def pet(self):
      print "Ouch! You bit me!"
We have the Snake class and the Cobra class that inherits from Snake. This illustrates the cobra is a snake. Now we can do this:-

>>> sly=Cobra()         # create a dangerous fellow called sly
>>> sly.setName("Sly")  # give him a name
>>> sly.name
'Sly'
>>>
The code above shows that the object sly inherited the function setName() from the Snake class. Now, let's pet this magnificant snake:-

>>> sly.pet()           # are you mad?
Ouch! You bit me!       
>>>
To conclude inheritance let's create another inherited snake and pet it too:-

>>> class Python(Snake):                    # Python inherits from a Snake
...     def pet(self):
...             print "Ouch! Stop crushing me!"
...
>>>
>>> monty=Python()
>>> monty.setName("Monty")
>>> monty.name
'Monty'
>>> monty.pet()
Ouch! Stop crushing me!
>>>

Let's move on before you lose consciousness. We've seen the dir() function earlier. Type the following to reveal class properties and functions:-

>>> dir(Snake)
['__doc__', '__init__', '__module__', 'setName']
>>>
>>> dir(Cobra)
['__doc__', '__init__', '__module__', 'setName', 'pet']
>>>
>>> dir(Python)
['__doc__', '__init__', '__module__', 'setName', 'pet']
>>>
Notice how the classes Cobra and Python inherit the function setName() AND the constructor __init__()

Polymorphism

The code below illustrates polymorphism using our snake classes.

>>> aSnake=Snake()      # create 3 snakes
>>> monty=Python()
>>> sly=Cobra()
>>>
>>> sly.pet()           # pet sly and monty
Ouch! You bit me!       
>>> monty.pet()
Ohh! Stop crushing me!
>>>
>>>
>>> aSnake=monty        # aSnake is a reference to monty
>>> aSnake.pet()
Ohh! Stop crushing me!
>>>
>>> aSnake=sly          # aSnake is now a reference to sly
>>> aSnake.pet()
Ouch! You bit me!
>>>

Some Light Relief

We've all come across the popular file compression format - ZIP. Python makes interacting with ZIP archive files really easy and fun! In this section we'll create, extract and add files to a ZIP archive.

Here's how to create a ZIP archive called python.zip and then how to add the file snake.py to it:-

>>> import zipfile
>>> zip = zipfile.ZipFile('python.zip','w')
>>> zip.write('snake.py')
>>> zip.close()
>>>
Now, go find python.zip and open it. Amazingly easy or what? Let's extract snake.py from ZIP archive - a little more complex:-

>>> zip = zipfile.ZipFile('python.zip','r')
>>> file('snake.py','w').write(zip.read('snake.py'))
>>> zip.close()
>>>
Finally, how about a Python program (Listing Python ZIP)to ZIP all files in the current directory into python.zip.

*** Python ZIP ***

import os
zip = zipfile.ZipFile('python.zip','w')
for file in os.listdir('.'):
   if(file!='python.zip'):   # don't add python.zip to itself
      print file             # will print the filenames
      zip.write(file)        # add to ZIP
zip.close()
Do that in Java or C++. How much code and time would it take?

C++ Primer

C and Java are your C++ primers.

C++ Object-Oriented Programming

Introduction

Over the years I've been describing C++ as the monster programming language that shouldn't be let loose on poor helpless students. But, here I am willing to revisit an old friend/foe. I hope to set a background to further topics like XML parsing and database programming. To guide me, the book I use is Horstmann's [1]. But maybe these notes are like those scary movies - the big bad monster inevitably is going to get us all in the end!?

So let's begin with the classic hello world program, Listing C++ Hello World .

*** C++ Hello World ***

#include <iostream>

using namespace std;

int main()
{
   cout << "hello, world!" << endl;
   return 0;
}
 

Painless really! So what's all the fuss about? Other programming structures such as if statements, loops, etc. are the same a Java/C.

C++ IDE

I used the GNU C++ Compiler to test the code here but you'll need to use SCiTE.

Classes

Let's look at a class in C++. The quintessential Cube class is a good starting point, Listing C++ Hello World. .

*** C++ Cube.cpp ***

class Cube
{
public:
   Cube();
   void setSide(double s);
   double getSide() const;
   double Area() const;
private:
   double Side;
};

Cube::Cube()
{
   Side=0.0;
}

void Cube::setSide(double s)
{
   Side = s;
}

double Cube::getSide() const
{
   return Side;
}

double Cube::Area() const
{
   return 6 * Side * Side;
}

#include <iostream>

using namespace std;


int main()
{
   cout << "Hello World!" << "\n";
   Cube cube;// = new Cube();
   cube.setSide(2.0);
   cout << cube.getSide() << "\n";
   cout << cube.Area() << "\n"; 
   return 0;
}
Running this gem produces :-
Hello World!
2
24

Interface

Let's look at the code in more detail. The code snipet below is known as the interface.
class Cube
{
public:
   Cube();
   void setSide(double s);
   double getSide() const;
   double Area() const;
private:
   double Side;
};
The interface of Cube consists of the methods (functions) you can call. The public functions. So the functions available are - the default constructor Cube(), setSide(), getSide() and Area().

The function setSide() is a mutator function. A mutator function is one that modifies the state of the object. In this case setSide() changes the Side member variable.

The function getSide() and Area() are accessor functions. A accessor function is one that queries the object without modifying its state. Notice that all accessor functions have the keyword const after its name. This is standard practice.

That's the interface. The actual code itself is implemented separately.

Implementation

Every member function declared in a interface must be written somewhere. The code below shows the implementation of the Cube functions:-
Cube::Cube()
{
   Side=0.0;
}

void Cube::setSide(double s)
{
   Side = s;
}

double Cube::getSide() const
{
   return Side;
}

double Cube::Area() const
{
   return 6 * Side * Side;
}

The prefix Cube:: indicates we are implementing a function.

Encapsulation

The Cube class stored the Side member variable in the private section of the class definition :-
private:
   double Side;

Because the Side variable is private. Only the functions actually in the class can access it. This is old hat to you by now! All data access must occur through the public functions. The act of hiding data and accessing it via functions is called encapsulation.

Constructors

We've seen one already (the default constructor):-

Cube::Cube()
{
   Side=0.0;
}

You can also have a constructor with parameters. For example :-

Cube::Cube(double s)
{
   Side=s;
}
can be used to create a Cube object and set the Side variable.

Inheritance

Again, not much mystery here. To illustrate inheritance we've created a class called SmallCube that inherits from Cube :-
class SmallCube : public Cube
{
public:
  SmallCube();

private:
  int colour;
};

SmallCube::SmallCube()
{
   colour=0;
}
In the first line, the : symbol denotes inheritance. SmallCube is inheriting from Cube. The class has a constructor that just initialises the only member variable colour.

Here's some code that uses the new class SmallCube:-

  
  SmallCube smallcube;
  smallcube.setSide(3.0);
  cout << "side=" << smallcube.getSide() << endl;
  cout << "area=" << smallcube.Area() << endl;
Notice that it uses the inherited functions - setSide(), getSide() and Area().

Polymorphism

Program Listing C++ Polymorphism illustrates polymorphism in action (courtesy of virtual functions).

*** C++ Polymorphism ***

class Employee
{
public:
  Employee();
  
  double getSalary() const;
  void setSalary(double);
  virtual double calculateSalary() const;
private:
  double salary;
};
Employee::Employee()
{
   salary=0;
}
double Employee::getSalary() const
{
   return salary;
}
void Employee::setSalary(double s)
{
   salary=s;
}
double Employee::calculateSalary() const
{
   return salary;
}
/* *********************************************************** */
/* *********************************************************** */
/* *********************************************************** */
class Manager : public Employee
{
public:
  virtual double calculateSalary() const;
};
double Manager::calculateSalary() const
{
   return getSalary()*2;
}
/* *********************************************************** */
/* *********************************************************** */
/* *********************************************************** */
#include <iostream>

using namespace std;

int main()
{
   Employee* e = new Employee();   // points to instance of base class
   e->setSalary(100000);
   cout << e->calculateSalary() << endl; 
   delete(e); //clean up
   
   e = new Manager();              // now points to an instance of derived class
   e->setSalary(100000);
   cout << e->calculateSalary() << endl;   
   delete(e); //clean up
   return 0;
}
When run, the output is going to be:-
100000
200000
Although e is a pointer to Employee, it uses the Manager version of calculateSalary(). The base class Employee and the derived class Manager declare a virtual function calculateSalary(). Polymorphism happens when at runtime the correct calculateSalary()function is chosen based upon the object being pointed to.

The moral of this code is that management always get more money.

Function Overloading

You've already seen a instance of function overloading. The constructor for the Cube class has two constructors (functions) that illustrate overloading :-
Cube::Cube()
{
  Side=0.0;
}

Cube::Cube(double s)
{
  Side=s;
}
As a result either constructor can be called at runtime. A further example is given with the constructors in SmallCube shown here :-
SmallCube::SmallCube()
{
   colour=0;
}

SmallCube::SmallCube(double side)
{
   colour=0;
   setSide(side);
}

SmallCube::SmallCube(double s,int c)
{
   colour=c;
   setSide(s);
}

Completed Code

See Listings CubeMain.cpp , Cube.hpp , SmallCube.hpp .

*** CubeMain.cpp ***

#include <iostream.h>

#include "Cube.hpp"
#include "SmallCube.hpp"

//using namespace std;

int main()
{
  cout << "*Cube*" << endl;
  Cube cube(10.0);  
  cout << "side=" << cube.getSide() << endl;
  cout << "area=" << cube.Area() << endl;

  cout << endl << "*SmallCube*" << endl;
  SmallCube smallcube;
  smallcube.setSide(3.0);
  cout << "side=" << smallcube.getSide() << endl;
  cout << "area=" << smallcube.Area() << endl;

  cout << endl << "*dice - Polymorphism*" << endl;
  Cube dice;
  dice=cube;
  cout << "side=" << dice.getSide() << endl;
  cout << "area=" << dice.Area() << endl;

  cout << endl << "*smalldice - Polymorphism*" << endl;
  dice=smallcube;
  cout << "side=" << dice.getSide() << endl;
  cout << "area=" << dice.Area() << endl << endl;

  return 0;
}
*** Cube.hpp ***
class Cube
{
public:
  Cube();
  Cube(double s);
  void setSide(double s);
  double getSide() const;
  double Area() const;

private:
  double Side;
};

Cube::Cube()
{
  Side=0.0;
}

Cube::Cube(double s)
{
  Side=s;
}

void Cube::setSide(double s)
{
  Side = s;
}

double Cube::getSide() const
{
  return Side;
}

double Cube::Area() const
{
  return 6 * Side * Side;
}
*** SmallCube.hpp ***
class SmallCube : public Cube
{
public:
  SmallCube();
  SmallCube(double);
  SmallCube(double,int);

private:
  int colour;
};

SmallCube::SmallCube()
{
   colour=0;
}

SmallCube::SmallCube(double side)
{
   colour=0;
   setSide(side);
}

SmallCube::SmallCube(double s,int c)
{
   colour=c;
   setSide(s);
}

Java and Python - A Comparative Review

Background

This document has been reused and modified from the original paper created by Ariel Partners http://www.arielpartners.com/arielpartners/content/public/home. It compares and contrasts the features of two programming languages - Python and Java. The document explores the areas of applicability of the two languages and examines where and how they compete.

At the time of writing this document the author has favourable opinions that Python should be used as the FIRST programming language at LYIT. Python syntax is clear and concise and even fun to use. Also, in this module - Comparative Programming - we have used Python to conduct essential programming tasks such as GUI, XML and database programming. The author would like to think that introducing Python, even at the final year of a under-graduate degree, has been a worthy (even enjoyable) exercise.

No one programming language is appropriate for every kind of task. Given the wide variety of problems to be solved, it is likely that every programmer will use at least two, and perhaps many more, programming languages on a daily basis. Given this fact, finding the right minimum combination of languages that solves the widest possible variety of programming chores is of paramount importance.

As you read this document remember that it is the original author's opinion that Python is the better choice for most common programming tasks, and Java should be used in those situations where Python is not appropriate, for example :-

Introduction

Why compare Java to Python? Do they compete? In the minds of many programmers, they are complementary. For example, consider the following quote from Mark Lutz (Learning Python) - Python doesn't compete head-on with Java; Python is a scripting language, Java is a systems language such as C++.

Of course, this statement was made in March of 1999. Many years later, Python has grown up. Most people agree that Python syntax generally allows for more concise programs; in fact programs written in Python are usually three to five times shorter than those written in Java. Given the critical importance of development speed, one must question whether Java really is the better choice for a general purpose software development language. The main question to be answered is the following - for which types of programming tasks is Java the better choice?

In order to answer this question, we must examine the languages along several different axes, including:-

Language Overviews

Python

Python is an interpreted, interactive, object-oriented programming language. It is often compared to Perl or Java.

Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as well as to various windowing systems (Tk, MFC). New built-in modules are easily written in C or C++.

The Python implementation is portable: it runs on many brands of UNIX, on Windows, DOS, OS/2, Mac, etc. Because it is written in ANSI C, it has been ported to virtually every popular system platform. Python is copyrighted but freely usable and distributable, even for commercial use.

Java

Java, by contrast, is both a programming language and a platform. The Java programming language is a high-level language that can be characterized by all of the following buzzwords - simple (;),architecture neutral,object oriented,portable,distributed,high performance,multithreaded,robust,dynamic and secure. Secure

We say Java is a platform because it does not expose low level system platform details to the programmer, rather it provides an abstract "virtual machine" that provides a generic interface to most of the functionality that is commonly available in today's computing environments. While this satisfies the needs of most application developers, it makes Java an inappropriate choice for system software such as device drivers and other scenarios where direct access to low-level functions is needed.

Similarities

An experienced Java programmer will find much that is familiar about the Python language and programming environment. Python is typically file-based, with a one-to-one correspondence between a Python module and source file. Python is compiled to portable byte code and run in a virtual machine. Both Java and Python were born in the year 1990. Like Java, Python is available on all of the volume platforms. Like Java, Python includes implementations of standard OOP concepts: classes, methods, inheritance, polymorphism, exceptions, and collections.

Learning the Language

Compare and contrast the code for "hello world," traditionally the first program presented in a beginning programming course. See the Java Listing MyHello.java:-

*** MyHello.java ***

class MyHello
{
   public static void main(String[] args)
   {
      System.out.println("Hello, world");
   }
}
and then the Python code:-

print "Hello, world"
Learning Java is more difficult both because of the complex syntax, and because so many concepts must be mastered in order to even get started. By contrast, Python can be learned gradually, with new features introduced one at a time.

This makes Python an ideal first object-oriented programming language (OOPL) to learn. Going further, it may be faster to first teach beginners Python and then Java, rather than Java as a first OOPL. Such an approach is not new. In fact, studies conducted in the early 1990's showed that COBOL programmers became productive with C++ more quickly if they learned Smalltalk first rather than moving to C++ right away. Smalltalk and C++ are certainly different than Python and Java, but in many ways the analogy holds true.

+------------------------------------------------+
| Feature     |  C++         | Java    | Python  |
| ------------|--------------|---------|---------|
| Syntax      | very complex | complex | simple  |
| Compactness | verbose      | verbose | compact |
+------------------------------------------------+

Encapsulation

All Python attributes are public. Any attribute can be changed from anywhere, anytime, once the name is known. This can lead to less readable code. private attributes represent an attempt to enforce encapsulation. Java advocates will conclude that, since encapsulation is not enforceable in Python, Python code is not as maintainable as Java code. It is not safeguarding the code and is perhaps dangerous in the hands of a novice.

Python advocates may, on the other hand, respond by saying Python solved the enforcement problem by avoiding it and that Java does not do it effectively. Advocates may also argue that the absence of encapsulation makes OO programming with Python intuitive to learn. See the Java code Java Encapsulationand Python code Python Encapsulation.

*** Java Encapsulation ***

class Point{
   public int x;
   private int y;

   Point(){
     x=10;
     y=20;
   }
}
*** Python Encapsulation ***
class Point:
   def __init__(self):
      self.x=10		#public
      self._y=20	#private

Evolution vs Growth

Both Java and Python are developing extremely rapidly. Though there are not yet as many libraries available for Python as for Java, the core features of the Python language are evolving much more rapidly. There are several reasons for this. One is, half a million Python programmers versus three million Java programmers. But the most important may be the different ways Java and Python are used. Few large companies are writing critical business systems in Python, whereas many or most are doing just that with Java. This puts enormous pressure on JavaSoft to maintain the stability of the Java language features and central Java libraries. By contrast, new point releases of Python are available every three to four months, each with significant language improvements.

Of course, both Java and Python are rapidly expanding in size by increasing the number of "standard libraries" bundled with the language. Java, because of the larger community, is probably growing more rapidly than Python in this regard. Therefore we might say that Java is growing more rapidly while Python is evolving more rapidly.

Single vs Multiple Inheritance

Python supports multiple inheritance. This opens up complexities with name clashes. Identically named attributes from different base classes overwrite each other, in the order in which they are declared in the subclass declaration. By contrast, Gosling, the original inventor of Java, chose to avoid the problems C++ programmers experienced with multiple class inheritance, and instead fitted Java with single class inheritance and multiple interface inheritance. See Java inheritance code in code example Java Inheritanceand Python code example Python Inheritance.

*** Java Inheritance ***

//JAVA Single Inheritance
class Boat{
}

class RowingBoat extends Boat{
}


//JAVA Multiple Inheritance
interface Boat{
}
interface Aeroplane{
}

class FlyingBoat implements Boat,Aeroplane{
}
*** Python Inheritance ***
//PYTHON Single Inheritance
class Boat:
   pass

class RowingBoat(Boat):
   pass


//PYTHON Multiple Inheritance
class Boat:
   def floats(self):
      print "floats"

class Aeroplane:
   def floats(self):
      print "does not float"
  
class FlyingBoat(Boat,Aeroplane):
   pass
   
fb=FlyingBoat()
fb.floats()		# prints "floats"

Interfaces

An interfaces specification for a module as provided by Java describes the prototypes for the methods of the module. Few dispute the value of separation between interface and implementation in maintaining large programs. Python does not support interface specifications directly within the language.

Programmer Savvy

There is an implicit, but very significant philosophical difference between the two languages that only becomes clear through extended use - their attitude towards the programmer.

Java attempts to provide a large number of constraints, controls, and safeguards to protect the programmer. Class members are access controlled to enforce encapsulation. All Java code runs through a bytecode verifier where security checks may be applied. However, all of the constraints, component facilities, and safeguards come with a price: increased complexity. This makes the language more difficult for beginners, but may make errors less likely, whether caused through ignorance or malicious intent.

Python, by contrast, provides a wide open playing field. All class members are, in effect, public, meaning that objects and classes can be modified at runtime. Ultimately, this interesting mixture of simplicity, uniformity, and broad access produces an environment that is simple and intuitive yet extremely powerful. This makes Python very simple to learn, and quite comfortable for experts, but perhaps more dangerous for programmers of only intermediate skill.

Distributed Programming Support

The packages providing distributed programming support for Python are fewer and less mature than those available for Java. There are a few CORBA based products with Python, but there are no products that provide the breadth or scope and maturity comparable to the now ubiquitous J2EE platforms.

Java provides built in support for distributed programming and mobile code via Remote Method Invocation (RMI). At least one similar technology does exist for Python (Pyro), but there is no such facility offered as part of the standard Python distribution. The Pyro technology is maturing rapidly, but it is still primarily a one-man show and is not particularly well known.

There is a huge variety of tools and technologies available to the Java programmer for building distributed, enterprise applications. From simple RMI and servlets to J2EE application servers.

Documentation and Visual Modeling tools

Javadoc represents a real advance in software engineering. When you consider Javadoc (and all of the available third-party add-ons and extensions thereof) along with all of the available CASE tools for visual modeling (such as Rational Rose or Together), Java has a formidable edge when it comes to documentation. Given that many of the typical problems in software development stem from poor communication, one would have to agree these tools can be extremely important.

There is a Javadoc-like tool bundled with Python, pydoc, but it has far fewer features and is not extensible in the way Javadoc is. As far as I can tell, there are no visual modeling tools that graphically model Python code (although many of the Java tools use Python or Jython for scripting). By contrast, there are probably a dozen major graphical modeling tools for Java, including several freeware/open source efforts.

Integrated Development Environments

The Java developer looking for an Integrated Development Environment enjoys a particularly robust set of choices, both commercial and open source/freeware.

Unfortunately, Python developers face a rather different scenario. Debugging in Python is reminiscent to debugging in Java about three years ago- poor at best. The emacs portable debugger (pdb) support is marginal, and the IDLE debugger (a freebie mini-IDE written by Guido and bundled with Python) is incomplete. A commercial IDE with some solid features does exist (PythonWorks).

Static v Dynamic Typing

Leaving aside the religious part of the static typing vs dynamic typing argument, it seems that the main issue for Python is one of efficiency. Because it was originally designed as a scripting language, rather than a systems language, features were designed for ease and flexibility rather than efficiency. In general, Python values maintainability more highly than efficiency.

On the other hand, Java has several features that, when used properly, render it nearly as efficient as C++.

Bertrand Meyer offers a particularly scathing rebuttal of the argument for dynamic typing. In his view, static typing increases reliability, readability, and efficiency.

Look at the Java code Java Typingand Python code Python Typing.

*** Java Typing ***

int a=10;
int b=20;
int c=a+b;

*** Python Typing ***

a=10
b=20
c=a+b

Java uses static typing where variable data types are know at compile time. Whereas Python uses dynamic typing where variable data types are know at run time. In the code above, Python must inspect the variables a and b to find their type and then perform the addition operation. On the other hand, Java knows the variables type since compile time and so it performs the addition operation faster.

Performance Issues

Many of Python's performance issues stem from the fact that Python interpreters and compilers are generally not as sophisticated nor as highly tuned for performance as those available for Java. However, there are ways of improving the performance of a particular Python program like recompiling the program using a JIT (just in time) compiler. Of coarse this still has limitations and drawbacks that may make them inappropriate for a given program, so the performance issue should certainly be given due consideration.

Jython enables a programmer to write Python code that is dynamically or statically compiled to Java bytecodes, and it provides an intriguing alternative to using the standard C-Python virtual machine. However, Jython can never be quite as fast as pure Java because of the added overhead of the Python-to-Java translation machinery. In addition, there are other potential problems with Jython like language limitations, missing features, lags behind Python releases, Java VM incompatibilities, etc.

Lack of support for Security

Python provides extremely limited support for security. By contrast, Java features comprehensive support for enforcing security at multiple levels. Of course, via Jython, the Python programmer automatically gains access to these and all other Java features. However, C-Python does not yet include support for such features in the standard library.

Conclusions

Java was designed to be an incremental step up from C++, with the rationale that for the price of a small bit of efficiency, you gained a huge amount in terms of simplicity, ease of development, maintainability, and portability. Python on the other hand offers a beautifully simple, clean design that can result in programs that are extremely clear, easy to maintain and very quick to develop.

Assuming current trends continue like computer hardware continues to improve apace, and Python continues to become more robust, powerful, and efficient, the number of computing problem spaces for which Python is a viable solution will grow.

Java and C++ - A Comparative Review

Bibliography

1
Cay Horstmann and Timothy Budd.
Big C++.
Wiley, 2005.

2
Bertrand Meyer.
Object-Oriented Software Construction, Second Edition.
Prentice Hall, 1997.

3
Sun Microsystems.
The Java Tutorials.
Sun Microsystems.

4
Patrick Niemeyer and Jonathan Knudsen.
Learning Java, Second Edition.
O'Reilly, 2002.

About this document ...

Comparison of Object-Oriented Progamming Languages
Comparative Programming Paradigms [COPPCO801]

This document was generated using the LaTeX2HTML translator Version 2002-2-1 (1.71)

Copyright © 1993, 1994, 1995, 1996, Nikos Drakos, Computer Based Learning Unit, University of Leeds.
Copyright © 1997, 1998, 1999, Ross Moore, Mathematics Department, Macquarie University, Sydney.

The command line arguments were:
latex2html OOPLs.tex -split 0 -no_navigation

The translation was initiated by tomo on 2008-09-10


tomo 2008-09-10