Object-oriented programming in Java (2)

Similar documents
Object-oriented programming in Java (3)

Object-oriented programming in...

Object-Oriented Programming Design. Topic : Graphics Programming GUI Part I

IT101. Graphical User Interface

CS 11 java track: lecture 3

G51PRG: Introduction to Programming Second semester Applets and graphics

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

CSE wi Final Exam 3/12/18 Sample Solution

Graphical User Interfaces 2

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Programming Languages and Techniques (CIS120)

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

H212 Introduction to Software Systems Honors

Final Examination Semester 2 / Year 2012

15CS45 : OBJECT ORIENTED CONCEPTS

Programmierpraktikum

Lecture 9. Lecture

Computer Science 210: Data Structures. Intro to Java Graphics

Programming Languages and Techniques (CIS120)

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Lecture 3: Java Graphics & Events

Come & Join Us at VUSTUDENTS.net

CSE wi Final Exam 3/12/18. Name UW ID#

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

First Name: AITI 2004: Exam 2 July 19, 2004

CMSC 132: Object-Oriented Programming II

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Java Programming Lecture 6

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Beyond CSE143. What s Left To Do? Templates. Using Templates. A Template Class. A Problem with Reusing Code CSE 143

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM)

+ Abstract Data Types

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Lecture 5: Java Graphics

Question 1. Show the steps that are involved in sorting the string SORTME using the quicksort algorithm given below.

Assignment 2. Application Development

Core Java Syllabus. Pre-requisite / Target Audience: C language skills (Good to Have)

Graphical User Interfaces 2

First Name: AITI 2004: Exam 2 July 19, 2004

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Graphical User Interfaces 2

VALLIAMMAI ENGINEERING COLLEGE

Java Swing Introduction

Introduction to the JAVA UI classes Advanced HCI IAT351

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

CSE 331 Software Design & Implementation

Assigned Date: August 27, 2014 Due Date: September 7, 2015, 11:59 PM

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Final Examination Semester 2 / Year 2011

The Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

AP CS Unit 11: Graphics and Events

2. (True/False) All methods in an interface must be declared public.

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphical User Interface (GUI)

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Graphical User Interface (GUI)

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Abstract Classes and Interfaces

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM

Fall Problem Set 1

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!

Exceptions - Example. Exceptions - Example

This page intentionally left blank

Object Orientated Programming in Java. Benjamin Kenwright

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Graphic Interface Programming II Events and Threads. Uppsala universitet

Graphical User Interfaces (GUIs)

Building a Java First-Person Shooter

CS 2110 Fall Instructions. 1 Installing the code. Homework 4 Paint Program. 0.1 Grading, Partners, Academic Integrity, Help

CSE 331 Final Exam 6/7/16

JFrame In Swing, a JFrame is similar to a window in your operating system

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

Fundamentals of Object Oriented Programming

GUI Output. Adapted from slides by Michelle Strout with some slides from Rick Mercer. CSc 210

Outline. Anonymous Classes. Annoucements. CS1007: Object Oriented Design and Programming in Java

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

Uppsala University. Assignment 3. Separation into Model-View TableModel ListModel ( multiple inheritance or adapter) Renderer (delegation)

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Shared Collection of Java Course Materials: New Topics Covered. Agenda

CS193k, Stanford Handout #3. Swing 1

Instruction to students:

SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

6.092 Introduction to Software Engineering in Java January (IAP) 2009

Chapter 11 Handling Exceptions and Events. Chapter Objectives

8359 Object-oriented Programming with Java, Part 2. Stephen Pipes IBM Hursley Park Labs, United Kingdom

Name Section. CS 21a Introduction to Computing I 1 st Semester Final Exam

Transcription:

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