Object-Oriented Programming with Java Exceptions, Strings and Things Lecture 4.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Advertisements

1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause.
Object-Oriented Programming with Java Java with added Swing Lecture 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
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.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Component-Based Software Engineering Using Interfaces Paul Krause.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 OOP : main concepts Polymorphism. 2 OOP : main concepts  The main concepts:  In a superclass –public members Accessible anywhere program has a reference.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
 2003 Prentice Hall, Inc. All rights reserved Case Study: Three-Level Inheritance Hierarchy Three level point/circle/cylinder hierarchy –Point.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
Component-Based Software Engineering Java with added Swing Paul J Krause.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
BY:- TOPS Technologies
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 14 – Exception Handling
Object-Oriented Programming with Java
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Object-Oriented Software Engineering
Exception Handling Contents
Chapter 11 Inheritance and Encapsulation and Polymorphism
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

Object-Oriented Programming with Java Exceptions, Strings and Things Lecture 4

More robust Classes  Declare fields as Private or Protected Protected fields can be accessed by subclasses or members of the same package Protected fields can be accessed by subclasses or members of the same package  Declare public “get” and “set” methods with appropriate checks on the “set” methods with appropriate checks on the “set” methods  E.g. public void setRadius(double radius) { checkRadius(radius); this.radius = radius; } this.radius = radius; }

public class Circle { public static final double PI = ; // a constant public static final double PI = ; // a constant protected double radius; protected double radius; protected void checkRadius(double radius) { protected void checkRadius(double radius) { if (radius < 0.0) { if (radius < 0.0) { throw new IllegalArgumentException("radius must not be negative"); } throw new IllegalArgumentException("radius must not be negative"); } } public Circle(double radius) { public Circle(double radius) { checkRadius(radius); checkRadius(radius); this.radius = radius; this.radius = radius; } public double getRadius() {return radius;} public double getRadius() {return radius;} public void setRadius(double radius) { public void setRadius(double radius) { checkRadius(radius); checkRadius(radius); this.radius = radius; this.radius = radius; } public double area() {return PI*radius*radius; } public double area() {return PI*radius*radius; } public double circumference() {return 2*PI*radius; } public double circumference() {return 2*PI*radius; }}

Catching Exceptions  Use the following construction: try { // code that may throw exceptions } catch (AnException e1) { // Code to handle this kind of exception } finally { // Code that will always execute }

Trying to succeed try { // Normally this block of code will be // executed successfully. // However, if an exception is thrown // execution will stop and the interpreter // will attempt to find an appropriate // “catch” statement. }

Catching Exceptions  There may be several “catch” blocks for different kinds of exceptions catch (AnException e1) { // This block will be invoked if an // AnException kind of exception is // thrown, or a sub-type of AnException. // The block can refer to the exception // object by its name “e1” }

And Finally finally { // This block contains code that will // always be run // - even if control leaves the “try” block // - even if control leaves the “try” block // because of a, or // because of a return, continue or // statement. // break statement. // It will, however, be skipped if there is a // It will, however, be skipped if there is a // System.exit( ) clause in the “try” block

public class MakeCircle { public static void main(String[ ] args) { public static void main(String[ ] args) { // details of input omitted // details of input omitted try { try { Circle circle = new Circle(radius); Circle circle = new Circle(radius); double area = circle.area( ); double area = circle.area( ); JOptionPane.showMessageDialog( JOptionPane.showMessageDialog( null, "The area equals " + area, null, "The area equals " + area, "Not a lot of people know that", JOptionPane.PLAIN_MESSAGE) ; } catch(IllegalArgumentException e1) { catch(IllegalArgumentException e1) { JOptionPane.showMessageDialog(null, "Radius must not be negative", JOptionPane.showMessageDialog(null, "Radius must not be negative", "Illegal argument", JOptionPane.ERROR_MESSAGE) ; } finally { finally { System.exit(0); System.exit(0); } }}

Some kinds-of Exception ExceptionClassNotFoundExceptionIllegalAccessExceptionRuntimeExceptionArithmeticExceptionArrayStoreException Illegal ArgumentException …

A little bit of formatting  With double precision numbers you may find you get outputs with an unrealistic degree of precision E.g. 7 figures after the decimal place E.g. 7 figures after the decimal place  This looks messy and the precision is normally meaningless

The java.text Package  As an example, we will use the DecimalFormat class from this package  Create an instance of DecimalFormat with the required format pattern  Invoke the “format” method of this instance to create a formatted string representation

import javax.swing.*; import java.text.DecimalFormat; public class MakeCircle { public static void main(String[ ] args) { public static void main(String[ ] args) { String input = JOptionPane.showInputDialog("Enter radius"); String input = JOptionPane.showInputDialog("Enter radius"); double radius = Double.parseDouble(input); double radius = Double.parseDouble(input); DecimalFormat twoDigits = new DecimalFormat( "0.00"); DecimalFormat twoDigits = new DecimalFormat( "0.00"); try { try { Circle circle = new Circle(radius); Circle circle = new Circle(radius); double area = circle.area(); double area = circle.area(); JOptionPane.showMessageDialog( JOptionPane.showMessageDialog( null, "The area equals " + twoDigits.format( area ), null, "The area equals " + twoDigits.format( area ), "Not a lot of people know that", JOptionPane.PLAIN_MESSAGE); "Not a lot of people know that", JOptionPane.PLAIN_MESSAGE); } // Rest of code omitted } One or more digits in front of the decimal point Only two digits behind the decimal point

Informing Exceptions  Remember that in the “main” method of MakeCircle, we explicitly included the error message: catch(IllegalArgumentException e1) { JOptionPane.showMessageDialog(null, "Radius must not be negative", JOptionPane.showMessageDialog(null, "Radius must not be negative", "Illegal argument", JOptionPane.ERROR_MESSAGE) ; }  Should not do this - there may be several different arguments that could throw the same exception type

 Inside Circle.java protected void checkRadius(double radius) { protected void checkRadius(double radius) { if (radius < 0.0) { if (radius < 0.0) { throw new IllegalArgumentException("radius must not be negative"); throw new IllegalArgumentException("radius must not be negative"); } }  Inside MakeCircle.java catch(IllegalArgumentException e1) { JOptionPane.showMessageDialog(null, e1.toString(), JOptionPane.showMessageDialog(null, e1.toString(), "Illegal argument", JOptionPane.ERROR_MESSAGE); "Illegal argument", JOptionPane.ERROR_MESSAGE); }

toString methods  Useful to define these for key classes  Provides an easy way of summarising the state of an instance of a class  Can by very useful for debugging

public class Point { // The notes show this class with more extensive commenting // The notes show this class with more extensive commenting protected double x, y;// Coordinates of the point accessible to subclasses protected double x, y;// Coordinates of the point accessible to subclasses public Point(double x, double y) { setPoint( x, y ); } public Point(double x, double y) { setPoint( x, y ); } // method sets the location of a point // method sets the location of a point public void setLocation(double xCoordinate, double yCoordinate) { public void setLocation(double xCoordinate, double yCoordinate) { x = xCoordinate; x = xCoordinate; y = yCoordinate; y = yCoordinate; } // conversion of a Point object to a string representation public String toString( ) { public String toString( ) { return("[" + x + ", " + y + "]"); }}

import javax.swing.*; public class MakePoint { public static void main(String[ ] args) { public static void main(String[ ] args) { String input; String input; input = JOptionPane.showInputDialog("Enter x Coordinate"); input = JOptionPane.showInputDialog("Enter x Coordinate"); double x = Double.parseDouble(input); double x = Double.parseDouble(input); input = JOptionPane.showInputDialog("Enter y Coordinate"); input = JOptionPane.showInputDialog("Enter y Coordinate"); double y = Double.parseDouble(input); double y = Double.parseDouble(input); try { try { Point point = new Point( x, y); Point point = new Point( x, y); JOptionPane.showMessageDialog( JOptionPane.showMessageDialog( null, "New point created: " + point.toString( ), null, "New point created: " + point.toString( ), "Pointed Message", JOptionPane.PLAIN_MESSAGE); "Pointed Message", JOptionPane.PLAIN_MESSAGE); } // rest of class definition omitted } // rest of class definition omitted

Adding properties to Points Point xyxy setLocation toString Location Circle radius area circumference plus Extension

public class Circle extends Point { public static final double PI = ; // a constant public static final double PI = ; // a constant protected double radius; protected double radius; protected void checkRadius(double radius) { // details omitted } protected void checkRadius(double radius) { // details omitted } public Circle(double x, double y, double radius) { public Circle(double x, double y, double radius) { super(x, y); super(x, y); checkRadius(radius); checkRadius(radius); this.radius = radius; this.radius = radius; } public String toString( ) {// Override Point.toString to add info. public String toString( ) {// Override Point.toString to add info. return "This is a Circle object with the following properties\n" + return "This is a Circle object with the following properties\n" + "Location: " + super.toString() + "\n" + "Location: " + super.toString() + "\n" + "Radius = " + radius + "\n"; "Radius = " + radius + "\n"; }}

main method of MakeCircle public void main(String[ ], args) { // … details omitted Circle circle = new Circle(x, y, radius); Circle circle = new Circle(x, y, radius); JOptionPane.showMessageDialog( JOptionPane.showMessageDialog( null, circle.toString( ), null, circle.toString( ), "Something New", JOptionPane.PLAIN_MESSAGE); "Something New", JOptionPane.PLAIN_MESSAGE); // and the rest... // and the rest...}

Interfaces  Sometimes we may find two or more different subclasses share some common behaviour  In this case, they are not strictly “kinds of” some common parent  Rather, they “behave like” some common pattern (under certain circumstances)  We say that they both implement a common interface

A “Cashier” Interface PersonMachine ATMEmployee «interface» Cashier withdraw deposit