Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.

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

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Class Hierarchy (Inheritance)
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Object-Oriented Programming and Class Hierarchies
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Inheritance and Class Hierarchies Chapter 3 Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 10 Classes Continued
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.
OOP Languages: Java vs C++
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Java and C++, The Difference An introduction Unit - 00.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
Slides Credit Umair Javed LUMS Web Application Development.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
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.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
CIS 2168 Data Structures and Algorithms in JAVA Object-Oriented Programming and Class Hierarchies.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
CIS 2168 Data Structures and Algorithms
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions  Create packages CS340 1

Java vs C# 2 CS340

The More Things Change The More They Stay The Same  We Are All Objects We Are All Objects  Keyword Jumble Keyword Jumble  Of Virtual Machines and Language Runtimes Of Virtual Machines and Language Runtimes  Heap Based Classes and Garbage Collection Heap Based Classes and Garbage Collection  Arrays Can Be JaggedArrays Can Be Jagged  No Global Methods No Global Methods  Interfaces, Yes. Multiple Inheritance, No. Interfaces, Yes. Multiple Inheritance, No.  Strings Are Immutable Strings Are Immutable CS340 3

The More Things Change The More They Stay The Same  Unextendable Classes Unextendable Classes  Throwing and Catching Exceptions Throwing and Catching Exceptions  Member Initialization at Definition and Static Constructors Member Initialization at Definition and Static Constructors CS340 4

The Same But Different  Main Method Main Method  Inheritance Syntax Inheritance Syntax  Run Time Type Identification (is operator) Run Time Type Identification (is operator)  Namespaces Namespaces  Constructors, Destructors and Finalizers Constructors, Destructors and Finalizers  Synchronizing Methods and Code Blocks Synchronizing Methods and Code Blocks  Access Modifiers Access Modifiers  Reflection Reflection  Declaring Constants Declaring Constants  Primitive Types Primitive Types  Array Declarations Array Declarations 5

Wish you were here…  Checked Exceptions Checked Exceptions  Cross Platform Portability (Write Once, Run Anywhere) Cross Platform Portability (Write Once, Run Anywhere)  Extensions Extensions  Dynamic Class Loading Dynamic Class Loading  Interfaces That Contain Fields Interfaces That Contain Fields  Anonymous Inner Classes Anonymous Inner Classes  Static Imports Array Declarations Static ImportsArray Declarations 6 CS340

Abstract classes CS340 7

Abstract Classes  Syntax: visibility abstract class className  Difference from other classes: An abstract class cannot be instantiated An abstract class may declare abstract methods  Includes abstract methods: visibility abstract resultType methodName (parameterList); CS340 8

Example of an Abstract Class public abstract class Food { public final String name; private double calories; // Actual methods public double getCalories () { return calories; } protected Food (String name, double calories) { this.name = name; this.calories = calories; } // Abstract methods public abstract double percentProtein(); public abstract double percentFat(); public abstract double percentCarbs(); } CS340 9

Interfaces, Abstract Classes, and Concrete Classes – Can an interface have: – abstract methods? (no body) – concrete methods? (with a body) – data fields Can an abstract class have: – abstract methods? (no body) – concrete methods? (with a body) – data fields Can a concrete class have: – abstract methods? (no body) – concrete methods? (with a body) – data fields CS340 10

Abstract Classes and Interfaces Can an interface – be instantiated? – declare abstract methods? Can an abstract class – be instantiated? – declare abstract methods? Can an interface have constructors? Can an abstract class have constructors? Can an abstract class implement an interface? Can an interface implement an abstract class? CS340 11

Inheriting from Interfaces vs Classes  A class can extend 0 or 1 superclass  An interface cannot extend a class  A class or interface can implement 0 or more interfaces CS340 12

Summary of Features of Actual Classes, Abstract Classes, and Interfaces CS340 13

Class Object and Casting 14 CS340

Class Object  Object is the root of the class hierarchy  Every class has Object as a superclass  All classes inherit the methods of Object but may override them CS340 15

Method toString  You should always override toString method if you want to print object state  If you do not override it:  Object.toString will return a String  Just not the String you want! Example: The name of the instance’s hash code CS340 16

Operations Determined by Type of Reference Variable  Java is strongly typed Object athing = new Integer(25);  What is the type of the variable athing ? CS340 17

Operations Determined by Type of Reference Variable (cont.)  Why does the following generate a syntax error? Integer aNum = aThing; CS340 18

Casting in a Class Hierarchy  Casting does not change the object!  It creates an anonymous reference to the object Integer aNum = (Integer) aThing; CS340 19

Using instanceof to Guard a Casting Operation instanceof can guard against a ClassCastException Object obj =...; if (obj instanceof Integer) { Integer i = (Integer) obj; int val = i;...; } else {... } CS340 20

Method Object.equals  Object.equals method has a parameter of type Object public boolean equals (Object other) {... }  Compares two objects to determine if they are equal  A class must override equals in order to support comparison CS340 21

Employee.equals() /** Determines whether the current object matches its obj The object to be compared to the current true if the objects have the same name and address; otherwise, return false public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() == obj.getClass()) { Employee other = (Employee) obj; return name.equals(other.name) && address.equals(other.address); } else { return false; } 22

A Java Inheritance Example—The Exception Class Hierarchy 23 CS340

Run-time Errors or Exceptions  Run-time errors  occur during program execution (i.e. at run-time)  occur when the JVM detects an operation that it knows to be incorrect  cause the JVM to throw an exception  Examples of run-time errors include  division by zero  array index out of bounds  number format error  null pointer exception CS340 24

Class Throwable  Throwable is the superclass of all exceptions  All exception classes inherit its methods CS340 25

Checked and Unchecked Exceptions  Checked exceptions  normally not due to programmer error  Must be explicitly caught  all input/output errors are checked exceptions  Extend class java.lang.Exception  Examples: IOException, FileNotFoundException CS340 26

Checked and Unchecked Exceptions (cont.)  Unchecked exceptions result from  programmer error (try to prevent them with defensive programming).  They do not have to be caught  a serious external condition that is unrecoverable  Extend class java.lang.RuntimeException  Examples: NullPointerException, ArrayIndexOutOfBoundsException CS Checked and unchecked exceptions are functionally equivalent. There is nothing you can do with checked exceptions that cannot also be done with unchecked exceptions, and vice versa.

Checked and Unchecked Exceptions (cont.)  Class Error : due to serious external conditions  Example: OutOfMemoryError  Unchecked exception  The class Exception and its subclasses can be handled by a program  RuntimeException and its subclasses are unchecked CS340 28

Some Common Unchecked Exceptions  ArithmeticException: division by zero, etc.  ArrayIndexOutOfBoundsException  NumberFormatException: converting a “bad” string to a number  NullPointerException  NoSuchElementException: no more tokens available CS340 29

Handling Exceptions  Exception example on eclipse (java tutorial book) CS340 30

The try-catch Sequence  The try-catch sequence resembles an if-then- else statement try { // Execute the following statements until an // exception is thrown... // Skip the catch blocks if no exceptions were thrown } catch (ExceptionTypeA ex) { // Execute this catch block if an exception of type // ExceptionTypeA was thrown in the try block... } catch (ExceptionTypeB ex) { // Execute this catch block if an exception of type // ExceptionTypeB was thrown in the try block... } 31

Using try-catch  Let’s try this example public static int getIntValue(Scanner scan) { int nextInt = 0; // next int value boolean validInt = false; // flag for valid input while(!validInt) { try { System.out.println("Enter number of kids: "); nextInt = scan.nextInt(); validInt = true; } catch (InputMismatchException ex) { scan.nextLine(); // clear buffer System.out.println("Bad data-enter an integer"); } return nextInt; } CS340 32

Packages and Visibility 33 CS340

Packages  A Java package is a group of cooperating classes  The Java API is organized as packages  Syntax: package classPackage;  Classes in the same package should be in the same directory (folder)  The folder must have the same name as the package  Classes in the same folder must be in the same package CS340 34

Packages and Visibility  Packages need to be imported  For example, x = Java.awt.Color.GREEN;  If the package is imported, the packageName prefix is not required. import java.awt.Color;... x = Color.GREEN; CS340 35

The Default Package  Files which do not specify a package are part of the default package  If you do not declare packages, all of your classes belong to the default package  Bad programming practice:  All your classes belong to the default package! CS340 36

Visibility Supports Encapsulation  Visibility rules enforce encapsulation in Java  private : for members that should be invisible even in subclasses  package: shields classes and members from classes outside the package  protected : provides visibility to extenders of classes in the package  public : provides visibility to all CS340 37

Visibility Supports Encapsulation (cont.)  Encapsulation insulates against change  Greater visibility means less encapsulation  So… use the most restrictive visibility possible to get the job done! CS340 38