Java and Jython translations

The following table shows examples of translating Java to Jython.

Java Jython equivalent
import java.lang.Math;
from java.lang import Math

Java does not support multiple inheritance.

Jython supports multiple inheritance.

Class declaration:

public class Hello {
  private String name = "John Doe";

  Hello(String name) {
   this.name = name;
  }

  public void greeting() {
    System.out.println("Hello" + name);
  }
}

Class declaration:

class Hello:
  def __init__(self, name="John Doe"):
    self.name = name

  def greeting(self):
    print "Hello, %s" % self.name

The __init__ method is the constructor, and you can pass it default arguments for any arguments the user does not supply, as with the name argument. You can supply named parameters when you instantiate a class or call a method.

The self term is a reference to the current instance of the class. It is the equivalent of the Java this reference. Calling it self is a Jython convention. You can use any name. Unlike Java, Jython requires you to prefix any instance variable with self. Failing to provide the self prefix usually results in an exception. When creating a bound method, the first parameter to the method is always self.

Variables can be public, protected, or private.

In Jython, variables and class methods can either be public or private. There is no protected level of visibility as there is in Java. They are public by default. To make them private, you can prefix them with a double underscore. For example, the following variable is private:

self.__name = name

Variables have to be declared before use.

Variables do not have to be declared before use, nor do their types need to be declared. (They do, however, have to be assigned before use.) This is true both for local variables within a block, and for the data members of classes.

Method signature:

public int getID(String name) 

Method signature:

def getID(name) 

In Jython, types are not explicitly declared.

for (Iterator i; i.hasNext();) {
    i.next();
}
for i in list:

The for statement automatically iterates over Java Lists, Arrays, Iterators, and Enumerators.

The for statement requires a sequence. It has the range() and xrange() functions to make sequences for the for statement:

for x in range(10, 0, -1):
if (x >= 0)
  System.out.println(“x is valid for a factorial”);
else 
  System.out.println(“x is invalid for a factorial”);

The if statement also has the if-elif-else statement. The else is optional.

if x >= 0:
  print x, "is valid for a factorial"
else:
  print x, "is invalid for a factorial"

or

if x == 0:
   doThis()
elif x == 1:
   doThat()
elif x == 2:
   doTheOtherThing()
else:
   print x, "is invalid"
while( x < 20 ) {
  System.out.print("x : " + x );
  x++;   
}
while x<20:
  print x
  x = x+1

Jython has an additional else clause that is optional and is executed when the condition evaluates to false.

Related Links