DM537 Object-Oriented Programming. Peter Schneider-Kamp.

Similar documents
DM503 Programming B. Peter Schneider-Kamp.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM503 Programming B. Peter Schneider-Kamp.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Numbers Implicit This Static Methods and Fields Packages Access Modifiers Main Overloading Exceptions Etc.

Array. Prepared By - Rifat Shahriyar

CS159 Midterm #1 Review

Lesson 3: Accepting User Input and Using Different Methods for Output

Language Features. 1. The primitive types int, double, and boolean are part of the AP

public static void main(string[] args) throws FileNotFoundException { ArrayList<Vehicle> arrayofvehicles = new ArrayList<Vehicle>();

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Character Stream : It provides a convenient means for handling input and output of characters.

Introduction to Programming Using Java (98-388)

Programming II (CS300)

DM503 Programming B. Peter Schneider-Kamp.

Programming II (CS300)

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Introduction to Java. Nihar Ranjan Roy.

COP 3330 Final Exam Review

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Index COPYRIGHTED MATERIAL

1 Shyam sir JAVA Notes

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

More about JOptionPane Dialog Boxes

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2013

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

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

CH. 2 OBJECT-ORIENTED PROGRAMMING

CSC 1214: Object-Oriented Programming

15CS45 : OBJECT ORIENTED CONCEPTS

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Java for Non Majors Spring 2018

Java Fundamentals (II)

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

DM550 Introduction to Programming part 2. Jan Baumbach.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

MSc/ICY Software Workshop Exception Handling, Assertions Scanner, Patterns File Input/Output

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Recitation: Loop Jul 7, 2008

CS Programming I: File Input / Output

CS 113 PRACTICE FINAL

INHERITANCE AND EXTENDING CLASSES

What are Exceptions?

Java Object Oriented Design. CSC207 Fall 2014

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

CSC Java Programming, Fall Java Data Types and Control Constructs

F I N A L E X A M I N A T I O N

Selected Java Topics

Polymorphism. return a.doublevalue() + b.doublevalue();

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Programming in the Large II: Objects and Classes (Part 1)

Java Swing Introduction

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

1.00 Lecture 30. Sending information to a Java program

Data Types Reference Types

Java Bytecode (binary file)

Software and Programming 1

CS Programming I: File Input / Output

Chapter 5 Object-Oriented Programming

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman )

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

INTERFACES. 24-Dec-10 INTERFACES VS. INHERITANCE. Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman ) Interfaces: Inheritance:

EXCEPTIONS. Fundamentals of Computer Science I

RAIK 183H Examination 2 Solution. November 10, 2014

CS260 Intro to Java & Android 03.Java Language Basics

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Lecture 2: Java & Javadoc

CST141 Thinking in Objects Page 1

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Practice Midterm 1. Problem Points Score TOTAL 50

More on Java. Object-Oriented Programming

Reading Input from Text File

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

THE CONCEPT OF OBJECT

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Question 1 [20 points]

Input-Output and Exception Handling

Oracle 1z Java Standard Edition 5 Programmer Certified Professional Upgrade Exam. Practice Test. Version:

Introduction to Java Written by John Bell for CS 342, Spring 2018

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

RAIK 183H Examination 2 Solution. November 11, 2013

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Full file at

Transcription:

DM537 Object-Oriented Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm537/!

TYPE CASTS & FILES & EXCEPTION HANDLING 2

Type Conversion Java uses type casts for converting values (int) x: converts x into an integer Example 1: ((int) 127) + 1 == 128 Example 2: ((int) -3.999) == -3 (double) x: converts x into a float Example 1: ((double) 42) == 42.0 Example 2: (double) "42" gives compilation error (String) x: views x as a string Object o = "Hello World!"; String s = (String) o; 3

Catching Exceptions type conversion operations are error-prone Object o = new Integer(23); Strings s = (String) o; good idea to avoid type casts sometimes necessary, e.g. when implementing equals method use try-catch statement to handle error situations Example 1: String s; try { s = (String) o; catch (ClassCastException e) { s = "ERROR"; 4

Catching Exceptions use try-catch statement to handle error situations Example 2: try { double x; x = Double.parseDouble(str); System.out.println("The number is " + x); catch (NumberFormatException e) { System.out.println("The number sucks."); 5

Arrays array = built-in, mutable list of fixed-length type declared by adding [] to base type int[] speeddial; creation using same new as for objects size declared when creating array speeddial = new int[20]; also possible to fill array using { while creating it then length determined by number of filled elements speeddial = {65502327, 55555555; 6

Arrays array = built-in, mutable list of fixed-length access using [index] notation (both read and write, 0-based) size available as attribute.length int[] speeddial = {65502327, 55555555; for (int i = 0; i < speeddial.length; i++) { System.out.println(speedDial[i]); speeddial[i] += 100000000; for (int i = 0; i < speeddial.length; i++) { System.out.println(speedDial[i]); 7

Command Line Arguments command line arguments given as array of strings public class PrintCommandLine { public static void main(string[] args) { int len = args.length; System.out.println("got "+len+" arguments"); for (int i = 0; i < len; i++) { System.out.println("args["+i+"] = "+args[i]); 8

Reading from Files done the same way as reading from the user i.e., using the class java.util.scanner instead of System.in we use an object of type java.io.file Example (reading a file given as first argument): import java.util.scanner; import java.io.file; public class OpenFile { public static void main(string[] args) { File infile = new File(args[0]); Scanner sc = new Scanner(infile); while (sc.hasnext()) { System.out.println(sc.nextLine()); 9

Reading from Files Example (reading a file given as first argument): import java.util.scanner; import java.io.*; public class OpenFile { public static void main(string[] args) { File infile = new File(args[0]); try { Scanner sc = new Scanner(infile); while (sc.hasnext()) { System.out.println(sc.nextLine()); catch (FileNotFoundException e) { System.out.println("Did not find your strange "+args[0]); 10

Writing to Files done the same way as writing to the screen i.e., using the class java.io.printstream System.out is a predefined java.io.printstream object Example (copying a file line by line): import java.io.*; import java.util.scanner; public class CopyFile { public static void main(string[] args) throws new FileNotFoundException { Scanner sc = new Scanner(new File(args[0])); PrintStream target = new PrintStream(new File(args[1])); while (sc.hasnext()) { target.println(sc.nextline()); target.close(); 11

Throwing Exceptions Java uses throw (comparable to raise in Python) Example (method that receives unacceptabe input): static double power(double a, int b) { if (b < 0) { String msg = "natural number expected"; throw new IllegalArgumentException(msg); result = 1; for (; b > 0; b--) { result *= a; return result; 12

OBJECT ORIENTATION 13

Objects, Classes, and Instances class = description of a class of objects a Car is defined by model, year, and colour object = concrete instance of a class a silver Audi A4 from 2009 is an instance of Car Example (Car as Java class): public class Car { public String model, colour; public int year; public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; 14

Attributes attributes belonging to each object are member variables they are declared by giving their types inside the class public class Car { public String model, colour; public int year; visibility can be public, protected, package or private for now only public or private: public = usable (read and write) for everyone private = usable (read and write) for the class 15

Getters and Setters getter = return value of a private attribute setter = change value of a private attribute public class Car { private String model; public String getmodel() { return this.model; public void setmodel(string model) { this.model = model; 16

Getters and Setters very useful to abstract from internal representation public class Car { // built after 1920 private byte year; public int getyear() { return this.year >= 20? this.year + 1900 : this.year + 2000; public void setyear(int year) { this.year = (byte) year % 100; 17

Static Attributes attributes belonging to the class are static attributes declaration by static and giving their types inside the class public class Car { private static int number = 0; public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; Car.number++; public int getnumberofcars() { return number; 18

Initializing Global and Local Variables local variable = variable declared in a block global variable = member variable or static attribute all local and all global variables can be initialized public class Car { private static int number = 0; public String model = "Skoda Fabia"; public Car(String model, int year, String colour) { boolean[] wheelok = new boolean[4]; 19

Constructors objects are created by using new Car mine = new Car("VW Passat", 2003, "black"); Execution: Java Runtime Environment reserves memory for object constructor with matching parameter list is called constructor is a special method with no (given) return type public class Car { public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; 20

Constructors more than one constructor possible (different parameter lists) constructors can use each other in first line using this( ); public class Car { public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; public Car(String model, byte year, String colour) { this(model, year > 20? 1900+year : 2000+year, colour); 21

Overloading overloading = more than one function of the same name allowed as long as parameter lists are different different return types is not sufficient! public class Car { public void setcolour(string colour) { this.colour = colour; public void setcolour(string colour, boolean dark) { if (dark) { colour = "dark"+colour; this.colour = colour; 22

Printing Objects printing objects does not give the desired result System.out.println(new Car("Audi A1", 2011, "red")); method public String tostring() (like str in Python) public class Car { public String tostring() { return this.colour+" "+this.model+" from "+this.year; 23

PROJECT PART 1 24

Organizational Details exam project consisting of 2 parts both parts have to be passed to pass the course projects must be done individually, so no co-operation you may talk about the problem and ideas how to solve them deliverables: written 4 page report as specified in project description handed in electronically as a SINGLE PDF file deadline: Wednesday, December 5, 12:00 ENOUGH - now for the FUN part 25

Board Games: Tic Tac Toe & Co Tic Tac Toe: simple 2 player board game played on a 3 x 3 grid extended rules for n-way Tic Tac Toe: n players (n+1) x (n+1) grid 3 marks in a row, column, diagonal Goal: complete an implementation of n-way Tic Tac Toe Challenges: Interfaces, GUI, Array Programming 26

Board Games: Tic Tac Toe & Co Task 0: Preparation download and understand existing framework need to describe design in your report! Task 1: Bounding and Shifting Coordinates implement check whether position on board or not implement shift with given differential vector Task 2: Implementing the Board get mark for a position or check if it is free record the move of a player check whether there are any moves left check the winning condition 27

Board Games: Tic Tac Toe & Co Task 3: Testing the Game test game play for standard 2 player 3 x 3 Tic Tac Toe test game play for n-way Tic Tac Toe with n > 2 Task 4 (optional): Connect Four different simple board game can be implemented similar to Tic Tac Toe Task 5 (optional): Go rich board game in a league with chess can be implemented like this, too more challenging! 28

ADVANCED OBJECT-ORIENTATION 29

Object-Oriented Design classes often do not exist in isolation from each other a vehicle database might have classes for cars and trucks in such situation, having a common superclass useful public class Vehicle { public String model; public int year; public Vehicle(String model, int year) { this.model = model; this.year = year; public String tostring() {return this.model+" from "+this.year; 30

Extending Classes Car and Truck then extend the Vehicle class public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { this.colour = colour; // this makes NO SENSE public String tostring() { return this.colour; public class Truck extends Vehicle { public double maxload; 31

Class Hierarchy class hierarchies are parts of class diagrams for our example we have: is-a Object is-a Vehicle is-a Car Truck 32

Abstract Classes often, superclasses should not have instances in our example, we want no objects of class Vehicle can be achieved by declaring the class to be abstract public abstract class Vehicle { public String model; public int year; public Vehicle(string model, int year) { this.model = model; this.year = year; public String tostring() {return this.model+" from "+this.year; 33

Accessing Attributes attributes of superclasses can be accessed using this public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; public String tostring() { return this.colour+" "+this.model+" from "+this.year; 34

Accessing Superclass methods of superclasses can be accessed using super public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; public String tostring() { return this.colour+" "+super.tostring(); 35

Superclass Constructors constructors of superclasses can be accessed using super public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { super(model, year); this.colour = colour; public String tostring() { return this.colour+" "+super.tostring(); 36

Abstract Methods abstract method = method declared but not implemented useful in abstract classes (and later interfaces) public abstract class Vehicle { public String model; public int year; public Vehicle(string model, int year) { this.model = model; this.year = year; public String tostring() {return this.model+" from "+this.year; public abstract computeresalevalue(); 37

Interfaces different superclasses could have different implementations to avoid conflicts, classes can only extend one (abstract) class interfaces = abstract classes without implementation only contain public abstract methods (abstract left out) no conflict possible with different interfaces public interface HasValueAddedTax { public double getvalueaddedtax(double percentage); public class Car implements HasValueAddedTax { public double getvalueaddedtax(double p) { return 42000; 38

Interfaces public interface HasValueAddedTax { public double getvalueaddedtax(double percentage); public interface Destructible { public void destroy(); public class Car implements HasValueAddedTax, Destructible { public double getvalueaddedtax(double p) { return 42000; public void destroy() { this.model = "BROKEN"; 39

Interface and Class Hierarchy interfaces outside normal class hierarchy HasValueAddedTax Destructible Vehicle Car Truck 40

GRAPHICAL USER INTERFACES 41

HelloWorld Reloaded Java standard GUI package is Swing from popup message to professional user interface import javax.swing.*; public class HelloWorldSimple { public static void main(string[] args) { JOptionPane.showMessageDialog(null, "Hello World!"); more challenging to do anything more complicated multi-threaded event-driven model-based UI design :-o 42

Dialogs user dialogs are created using JDialog class basically like JFrame (next slide), but with a parent window often used via static JOptionPane methods Object[] options = {1, 2, 3, 4, 5, 10, 23, 42; Object result = JOptionPane.showInputDialog(null, "Select number", "Input, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); int selectedint = (Integer) result; 43

Creating a Window windows are represented by objects of class JFrame constructor gets title displayed at top of window JFrame window = new JFrame("My first window!"); window.setsize(400, 250); // set size of window to 700x400 window.setlocation(50, 50); // top-left corner at (50, 50) // exit program when window is closed window.setdefaultcloseoperation(jframe.exit_on_close); window.setvisible(true); // show window on the screen 44