COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Class Hierarchy (Inheritance)
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Lecture 9 Concepts of Programming Languages
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Programmer-defined classes Part 3. A class for representing Fractions public class Fraction { private int numerator; private int denominator; public Fraction(int.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
What is inheritance? It is the ability to create a new class from an existing class.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Java Programming: Guided Learning with Early Objects
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Case Study - Fractions Timothy Budd Oregon State University.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Introduction to Object Oriented Programming CMSC 331.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Types in programming languages1 What are types, and why do we need them?
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
COSC 1P02 Data Structures and Abstraction 2.1 Cosc 1P02 Binary Files & Persistent Objects “For myself, I am an optimist--it does not seem to be much use.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Classes, Interfaces and Packages
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
COP 3330 Notes 3/7. Today’s Topics Exceptions Abstract Classes.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Lecture 9 Concepts of Programming Languages
Java Programming Language
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Exception Handling in Java
Lecture 11 Objectives Learn what an exception is.
Exception Handling Contents
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Lecture 9 Concepts of Programming Languages
Presentation transcript:

COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for the first time. Friedrich Nietzsche

COSC 1P03 Data Structures and Abstraction 4.2 Data Abstraction  data abstraction  abstract data type (ADT)  data type  data structure  information hiding  reduction of complexity  security  modifiability  programming-by-contract  supplier vs client  specification vs realization  collection (container) types

COSC 1P03 Data Structures and Abstraction 4.3 Data Abstraction in Java  the class and information hiding  public vs private  class includes specification and implementation  modification  multiple implementations?  interface  specification only  defines a type  contract  exception  reporting contract violations (errors)  package  aggregation of interfaces and classes  e.g. dates

COSC 1P03 Data Structures and Abstraction 4.4 Package  collection of related interfaces and classes  libraries  syntax  package names  unnamed package  import .* - all public interfaces and classes in package  visibility  class modifiers  public or not  package visibility  implementation defined

COSC 1P03 Data Structures and Abstraction 4.5 Interface  defines a type  can declare variables of interface type  no implementation  cannot create objects of interface type  syntax  compilation unit  vs class specifications  constants and method headers only

COSC 1P03 Data Structures and Abstraction 4.6 Fraction ADT  not a built-in type  approximations: double  round-off error  when desire precise calculations  values  mixed fractions  of the form p/q where p & q are integers  operations  arithmetic: +, -, *, /  comparison  compatibility with other numeric types  conversions  string representation  conversion to/from

COSC 1P03 Data Structures and Abstraction 4.7 Testing Implementation Classes  test suites  based on interface definitions  testing exceptions  try / catch statement  syntax  effect  use More about Exceptions  Exception Hierarchy  Try Catch Examples

COSC 1P03 Data Structures and Abstraction 4.8 Fraction Interface  minimal set of operations  accessor methods  conversion  constructors for conversion  conversion methods  loss of information  explicit  comparison  arithmetic  methods  Fraction results  functional notation  e.g. e = f.mul(g).add(h)  intermediate objects  immutable

COSC 1P03 Data Structures and Abstraction 4.9 RationalFraction Class  as Rational numbers ( p/q, q  0 )  pair of integers  numerator ( num )  denominator ( denom )  multiple representations of same value?  1/2, 2/4, 3/6, …  1/2, -1/-2 and -1/2, 1/-2  0/1, 0/2, …  whole numbers  mixed fractions

COSC 1P03 Data Structures and Abstraction 4.10 RationalFraction Class.  canonical (normal) form  lowest terms  sign  zero  exception  constructors  constructor chaining  normalization  String to Fraction conversion  cannot chain  conversions  arithmetic  normalization  normalization  exception  sign  exclusive or ( ^ )  GCD

COSC 1P03 Data Structures and Abstraction 4.11 Testing Implementation Classes  Exception Handler  Test suites  based on interface definitions  Testing exceptions  try / catch statement  syntax  effect  use  Exception handling  debugging  “fail-soft”

COSC 1P03 Data Structures and Abstraction 4.12 Building Libraries .jar files  “java archive file”  collection of java.class files that makes up a library  Creating a.jar file  can create a.jar file from a project in DrJava and JCreator  Accessing a custom library  must be included on “classpath” (where Java compiler looks for libraries)  set property for client project in DrJava or JCreator

COSC 1P03 Data Structures and Abstraction 4.18 Try Catch Clause try statements A catch (exception_type1 identifier) statements B catch (exception_type2 identifier) statements C finally statements D We will try to execute Code A If the code succeeds then no exception is thrown, control passes to finally The statements in D are executed If statements A caused an exception, it must be caught, the returned exception type is matched to a catch clause. We can assume that exception_type1 was caught, so Statements B are executed Statements in finally are executed. Finally is used to do clean up should it be needed. Regardless of an exception or not these statements are executed. Optional statement.

COSC 1P03 Data Structures and Abstraction 4.19 Exception Examples try x = 4 / 0; catch (ArithmeticException e) system.out.println("Divide by zero"); try x = 4 / 0; catch (Exception e) system.out.println("Divide by zero"); try x = 4 / 0; catch (InvalidDateException e) system.out.println("Invalid date detected"); catch (Exception e) system.out.println("Divide by zero"); Will cause ArithmeticException ArithmeticException is caught Will cause ArithmeticException General exception, catches anything, outputs "Divide by zero" Will cause ArithmeticException Not an invalid date so we skip this handler This handler will trap any exception, so "Divide by zero" will be printed. Can also put ArithmeticException trap here, same result.

COSC 1P03 Data Structures and Abstraction 4.20 Exception Hierarchy Checked Exceptions: Compiler ensures that the user has an exception handler in place. Unchecked Exceptions: Up to the user to determine if checking for such an exception is necessary.

COSC 1P03 Data Structures and Abstraction 4.21 Package Interface specificatio n Defines the: Interface specification Defines the: -object -methods -constants Defines an interface object type Implementation of Object subtype 1 Implementation of Object subtype 2 Other classes interact package abc; import whatever.*

COSC 1P03 Data Structures and Abstraction 4.22 Fractions Interface package Fractions; public interface Fraction { public int numerator ( ); public int denominator ( ); public double doubleValue ( ); public int intValue ( ); public boolean equals ( Fraction f ); public int compareTo ( Fraction f ); public Fraction add ( Fraction f ); public Fraction sub ( Fraction f ); public Fraction mul ( Fraction f ); public Fraction div ( Fraction f ); } // Fraction

COSC 1P03 Data Structures and Abstraction 4.23 Rational Fraction package Fractions; import java.io.*; public class RationalFraction implements Fraction, Serializable { private int num; // the numerator of the fraction private int denom; // the denominator of the fraction /** This constructor produces the fraction 0 (i.e. 0/1). public RationalFraction ( ) { this(0,1); }; // constructor // This constructor produces the fraction n/1. public RationalFraction ( int n ) { this(n,1); }; // constructor // This constructor produces the fraction n/d. public RationalFraction ( int n, int d ) { num = n; denom = d; normalize(); }; // constructor //Produces an object from a String public RationalFraction ( String s ) { String n; // numerator as a string String d; // denominator as a string s = s.trim(); n = s.substring(0,s.indexOf('/')); d = s.substring(s.indexOf('/')+1); num = Integer.parseInt(n); denom = Integer.parseInt(d); normalize(); }; // constructor Each Time a new object is created it is normalized to a canonical form

COSC 1P03 Data Structures and Abstraction 4.24 Rational Fraction. public int numerator ( ) { return num; }; // numerator public int denominator ( ) { return denom; }; // denominator public double doubleValue ( ) { return (double) num / denom; }; // doubleValue public int intValue ( ) { return num / denom; }; // intValue public boolean equals ( Fraction f ) { return num == f.numerator() & denom == f.denominator(); }; // equals public int compareTo ( Fraction f ) { return num*f.denominator() - f.numerator()*denom; }; // compareTo public Fraction add ( Fraction f ) { return new RationalFraction(num*f.denominator()+f.numerator()*denom, denom*f.denominator()); }; // add Standard set of accessor methods, and pseudo attributes methods. For every calculation a new object is created based on the interface type.

COSC 1P03 Data Structures and Abstraction 4.25 Rational Fraction.. public Fraction sub ( Fraction f ) { return new RationalFraction(num*f.denominator()- f.numerator()*denom, denom*f.denominator()); }; // sub public Fraction mul ( Fraction f ) { return new RationalFraction(num*f.numerator(),denom*f.denominator()); }; // mul public Fraction div ( Fraction f ) { return new RationalFraction(num*f.denominator(),denom*f.numerator()); }; // div Same concept as add, return new objects.

COSC 1P03 Data Structures and Abstraction 4.26 Rational Fraction… public String toString ( ) { return num + "/" + denom; }; // toString toString is inherited from Object via the implicit extends. Programmer has the ability to implement this as they see fit, overloading the existing implementation which returns the serial number of the object.

COSC 1P03 Data Structures and Abstraction 4.27 Rational Fraction…. private void normalize ( ) { int sign; // sign for fraction int div; // divisor if ( denom == 0 ) { throw new ZeroDenominatorException(); }; if ( num == 0 ) { denom = 1; }; if ( (num < 0) ^ (denom < 0) ) { sign = -1; } else { sign = 1; }; div = gcd(Math.abs(num),Math.abs(denom)); num = sign * Math.abs(num) / div; denom = Math.abs(denom) / div; }; // normalize Only case where an illegal fraction can exist is when the denominator is zero, so we force an exception Ensure the sign is carried by the numerator Find the GCD and then normalize the fraction.

COSC 1P03 Data Structures and Abstraction 4.28 Rational Fraction….. /** This method determines the greatest common divisor (gcd) of two positive * integers. */ private int gcd ( int n, int m ) { while ( n != 0 & m != 0 ) { if ( n > m ) { n = n - m; } else { m = m - n; }; if ( n != 0 ) { return n; } else { return m; } }; // gcd Calculate and return the Greatest Common Divisor

COSC 1P03 Data Structures and Abstraction 4.29 Zero Denominator package Fractions; public class ZeroDenominatorException extends RuntimeException { private static final long serialVersionUID = L; protected String msg; public ZeroDenominatorException (String m){ msg=m; } public ZeroDenominatorException(){} public String toString(){ return msg; } In Blue the modified exception object, allowing a simple message to be included with the error. toString can be overloaded to provide a standardization with other java objects.

COSC 1P03 Data Structures and Abstraction 4.30 Testing the Package package Test_Fractions; import Fractions.*; import BasicIO.*; public class TestFractions { private ASCIIDisplayer out; /** The constructor opens an ASCIIDisplayer for the test. */ public TestFractions ( ) { out = new ASCIIDisplayer(); }; // constructor public void fractionTest ( ) { Fraction f, g, h; // fractions for testing int r; f = new RationalFraction(1,3); g = new RationalFraction("2/3"); h = f.add(g); [[[[ snip ]]]] try { h = g.div(f); out.writeString(h.toString()); } catch ( ZeroDenominatorException e ) { //out.writeString(" zero denominator"); out.writeString(e.msg); }; Extracting the message from the exception

COSC 1P03 Data Structures and Abstraction 4.31 The End