Chapter 7. Inheriting from Java

Inheritance and the resulting reuse of code is a key feature of object-oriented programming, supported both by Java and Python. The ability to create subclasses is vital to the flexible use of an object-oriented library. In particular, many Java libraries are designed so that inheriting their classes or implementing their interfaces is the best way to use them. GUI libraries (AWT or Swing) are prime examples of this.

To allow effective access to preexisting Java code, Jython supports direct inheritance from Java classes. This is done without any additional syntax and with natural extensions of the semantics explained so far.

Extending an existing Java class is as simple as putting the Java class name in the base classes list of a Jython class statement. The following Java code defines a Java class MentalState to be subclassed in Jython:

public class MentalState {

    public int energy;

    public MentalState(int e) {
        this.energy = e;
    }

    public int askEnergy( ) { return energy; }
}

The following Jython code actually defines a Jython subclass of MentalState. For the Jython code to work, MentalState must be in the Jython classpath.

import MentalState

class FlexibleMentalState(MentalState):
    pass

if __name__ == '__main__':
    flexible = FlexibleMentalState(3)
    print flexible.askEnergy( )

3

Similarly, implementing an interface is as simple as putting one or more interface names in the base classes list. The only restriction is that a Jython class can only be a subclass of, ...

Get Jython Essentials now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.