Programming Languages Week 13 Object-oriented programming in Java (2) College of Information Science and Engineering Ritsumeikan University
plan last week intro to Java advantages and disadvantages language features how it differs from Python basic syntax how it differs from Python exercises: write and run some simple programs this week polymorphism inheritance: extending library classes, superclass constructors interfaces errors and exceptions user interface next weeks more language features and syntax exercises: develop some progams that are fun and useful 2
polymorphism polymorphim means occurring in several different forms both functions and types (variables) can be polymorphic ad hoc polymorphism: overloaded functions same function name, multiple implementations each implementation has different parameter types argument types select which implementation to run double twice(double x) { return x + x; String twice(string x) { return x + x; System.out.println(twice(21.0)); // => 42.0 System.out.println(twice("he")); // => "hehe" 3
polymorphism parametric polymorphism: parameterised types e.g., arrays: a String[] contains Strings generalise this idea to any user-defined class MyClass<Type> some part of MyClass will be specialised to store/manipulate objects of Type often used with containers (classes that manage collections of objects) e.g., ArrayList can contain any type you like ArrayList<String> contains Strings ArrayList<Integer> contains Integers 4
polymorphism class Point<T> { T x, y; Point(T _x, T _y) { x = _x; y = _y; T getx() { return x; T gety() { return y; //...etc...a Point<double> mypoint = new Point<double>(3.3, 4.4); Point<int> yourpoint = new Point<int>(3, 4); Point<T> is a generic type within its implementation, T is type parameter (a placeholder for a type) when Point<T> is used, it must be parameterised by an actual type the compiler generates implementations of Point<T> for any T that is used T is a type parameter of Point<T> Point<double> and Point<int> are parameterised types the double and the int are type arguments 5
inheritance in Python, it is difficult to extend built-in or library classes in Java it is easy for convenience: to avoid typing a long name class Point extends Point2D.Double { to extend library classes beware: constructors are not inherited class Point extends Point2D.Double { Point(double x, double y) { super(x, y); // NOT INHERITED Point add(point other) { return new Point(x + other.x, y + other.y); Java syntax for calling the superclass constructor: super(args...) 6
in Python, state is not inherited inheritance is it added dynamically to object by the initialisation functions it is up to the programmer to manage initialisation from multiple base classes class X(A, B, C): def init (): A. init () # programmer knows B. init () # what they C. init () # are doing... in Java, state is inherited state within objects is not dynamic, it is a fixed property of the class every class inherits the instance variables of its superclass new instance variables can be added, but inherited ones cannot be removed class Point extends Point2D.Double { // instance variables x and y are inherited automatically 7
inheritance this leads to problems with multiple inheritance if two superclasses define the same instance variable, which one wins? if they are of different types, they cannot even be unified the Java solution: multiple inheritance is not supported you cannot have more than one superclass this is a disaster, because of static typing static typing is incompatible with duck typing need a way to indicate (statically) that an object quacks like a duck so that we can use it in any place where a duck is welcome just need to ensure the object behaves correctly the Java solution: interfaces 8
interfaces extends introduces a subclass: an is-a X relationship everything needed to be an X is inherited, including state implements promises certain behaviour: an acts-like Y relationship all methods expected of a Y are implemented; state is irrelevant conformance can be checked at compile time any number of interfaces can be implemented by a class its instances can play all the corresponding roles static form of duck typing 9
a couple of useful interfaces Runnable is the interface implemented by things that can become threads of execution a thread is a computation that runs in parallel with the rest of the program complex programs often have many threads active at the same time for an object to be Runnable is only has to implement void run() public class MyTask implements Runnable { public void run() { // do concurrent computation here Thread t = new Thread(new MyTask()); t.start(); // runs MyTask.run() concurrently 10
a couple of useful interfaces KeyListener is the interface implemented by objects that react to keyboard input when keys are pressed or released, the object is notified notification happens by calling a method, with a keyboard event as argument for an object to be a KeyListener is only has to implement three methods public class MyTypewriter implements KeyListener { public void keypressed(keyevent event) { // event contains code of the key that was pressed public void keyreleased(keyevent event) { // event contains code of the key that was released public void keytyped(keyevent event) { // event contains Unicode character of the key that was typed 11
exceptions in Python, when something goes wrong, an exception is raised e.g., array index out of bounds you can simply ignore exceptions at run-time they will cause a backtrace and program termination in Java, when something goes wrong, an exception is raised e.g., array index out of bounds you cannot ignore exceptions the compiler knows which exceptions are raised by which methods your program will not compile unless you deal with every possible exception 12
exceptions compiling this public class Example { public static void main(string[] args) { File file = new File("/Users/me/TopSecret.txt"); FileReader reader = new FileReader(file); causes this Example.java:4: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader reader = new FileReader(file); 13
exceptions to avoid these errors, catch the exceptions that Java wants you to try { // code that might raise an exception catch (ExceptionType e) { e.printstacktrace(); // deal with the exception here the easiest thing to do is print a stack trace and carry on especially if the error really is an error unfortunately, Java uses exceptions for things that are not really errors e.g., a file being missing when you try to open it 14
user interface Java comes with several powerful GUI libraries AWT the Abstract Window Toolkit thin wrapper around the native UI of your platform programs using it are not portable support classes (geometry, transforms, etc.) still useful Point has x and y Dimension has width and height Rectangle and various other shapes Swing platform-independent GUI toolkit many different styles, independent of platform programs using it are portable compatible with useful AWT classes JPanel a canvas within a frame that can be painted on make a subclass of this for drawing onto JFrame a window on the display create one of these, and add the subclass of JPanel 15
example import javax.swing.*; import java.awt.*; // JPanel, JFrame // Dimension, Graphics[2D], Color public class Example extends JPanel { public static void main(string[] args) { new Example(); public Example() { JFrame frame = new JFrame("Example"); // top-level window frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(this); // add our panel for drawing frame.pack(); // fit the frame to the panel frame.setvisible(true); // put the window on the screen repaint(); // draw its contents 16
example // JPanel methods public Dimension getpreferredsize() { return new Dimension(640, 480); // tell pack() how big we are public void paintcomponent(graphics g) // paint our content { super.paintcomponent(g); // in case our superclass has content Graphics2D g2d = (Graphics2D)g; // g is really a Graphics2D Dimension size = getsize(); // in case we are resized g2d.setpaint(color.black); // clear the background to black g2d.fillrect(0, 0, size.width, size.height); g2d.setpaint(color.red); // draw a rectangle in red g2d.drawrect(size.width/4, size.height/4, size.width/2, size.height/2); // class Example 17
18
exercises generic types exceptions interfaces starting Friday: final project 19